OntoBricks Architecture

Contents

Contents

Overview

OntoBricks is a web-based Graph Viewer Builder that runs natively on Databricks. The core workflow is:

  1. Design an ontology visually (or import one from OWL / industry standards).
  2. Map ontology entities to Unity Catalog tables using R2RML.
  3. Materialize a triple store (Delta table) and a graph backend (Lakebase Postgres).
  4. Explore the resulting graph viewer — visual navigation, SPARQL, GraphQL, data-quality checks, and reasoning.

Under the hood, SPARQL translates ontology mappings into Spark SQL — users never need to write SPARQL themselves.

High-Level Architecture

Architecture Overview

Layer What it does
User Interface Bootstrap 5.3 + OntoViz visual editor + Sigma.js / D3.js graph views
MCP Server Separate Databricks App (mcp-ontobricks) exposing knowledge-graph tools to LLM clients (Cursor, Claude Desktop, Playground)
FastAPI Application Routes → Domain Objects → Core layered architecture with GlobalConfigService, PermissionService, and BuildScheduler
LLM Agents MLflow-traced agentic loops for ontology generation, auto-mapping, icon mapping, and conversational assistance
Reasoning Engine OWL 2 RL deductive closure, SWRL rules (compiled to SQL), graph reasoning, and constraint validation
Triple Store Backends Delta-backed view in Unity Catalog plus a per-domain pluggable Graph DB engine (Lakebase Postgres, Unity Catalog Delta, or Neo4j) via the GraphDBFactory pattern, with BFS, shortest path, and transitive closure built in
Databricks Platform Unity Catalog (metadata & governance), SQL Warehouse (query execution), UC Volumes (shared storage)
GitHub mirror (optional) One repository per instance; coalesced commits of registry JSON plus generated OWL/R2RML Turtle. Lakebase stays the source of truth.

Semantic Web Standards Stack

OntoBricks leverages multiple W3C semantic web standards to bridge relational data and graph viewers:

Semantic Web Stack

The stack shows how each layer builds upon the previous:

Layer Standard Role in OntoBricks
Query SPARQL Semantic query language (used internally for SQL generation)
Validation SHACL Shapes Constraint Language for data quality validation
Mapping R2RML Maps tables to RDF triples
Rules SWRL Horn-clause rules for inference and violation detection
Ontology OWL/RDFS Defines classes and properties
Data RDF Triple data model (S, P, O)
Storage SQL Delta view (Spark SQL) + Lakebase Postgres flat triple table

Key Standards Explained

1. RDF (Resource Description Framework)

What it is: The foundational data model for the semantic web. All data is expressed as triples: (Subject, Predicate, Object).

How OntoBricks uses it:

  • Entities become RDF resources with URIs (e.g., https://example.org/Person/P001)
  • Relationships become RDF predicates (e.g., :worksIn)
  • Generated using RDFLib library in Python

Example Triple:

<https://example.org/Person/P001> <https://example.org/worksIn> <https://example.org/Department/D001> .

2. OWL (Web Ontology Language)

What it is: A knowledge representation language for creating ontologies. Extends RDFS with richer semantics.

How OntoBricks uses it:

  • Visual Designer (OntoViz) creates ontologies visually
  • Form-based interface for detailed class/property definition
  • Classes defined as owl:Class
  • Properties defined as owl:ObjectProperty (relationships) or owl:DatatypeProperty (attributes)
  • Stored in Turtle (.ttl) format

Generated OWL Example:

@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix : <https://example.org/ontology#> .

:Person a owl:Class ;
    rdfs:label "Person" .

:worksIn a owl:ObjectProperty ;
    rdfs:domain :Person ;
    rdfs:range :Department .

OntoBricks Components:

  • OntologyGenerator (src/back/core/w3c/owl/OntologyGenerator.py) - Generates OWL from UI configuration
  • OntologyParser (src/back/core/w3c/owl/OntologyParser.py) - Parses existing OWL files
  • OntoViz (src/front/static/global/ontoviz/ontoviz.js) - Visual ontology designer

3. R2RML (RDB to RDF Mapping Language)

What it is: A W3C standard for expressing mappings from relational databases to RDF.

How OntoBricks uses it:

  • Mapping Page generates R2RML automatically
  • Maps Databricks tables to RDF classes
  • Maps columns to RDF properties
  • Maps SQL queries to relationships between entities
  • Supports relationship direction (forward, reverse, bidirectional)

R2RML Structure:

@prefix rr: <http://www.w3.org/ns/r2rml#> .
@prefix : <https://example.org/ontology#> .

# Entity Mapping (TriplesMap)
<#PersonMapping> a rr:TriplesMap ;
    rr:logicalTable [ rr:tableName "main.default.person" ] ;
    rr:subjectMap [
        rr:template "https://example.org/Person/{person_id}" ;
        rr:class :Person
    ] ;
    rr:predicateObjectMap [
        rr:predicate rdfs:label ;
        rr:objectMap [ rr:column "name" ]
    ] .

# Relationship Mapping (with SQL Query)
<#WorksInMapping> a rr:TriplesMap ;
    rr:logicalTable [ rr:sqlQuery """
        SELECT person_id, dept_id 
        FROM main.default.person_department
    """ ] ;
    rr:subjectMap [
        rr:template "https://example.org/Person/{person_id}"
    ] ;
    rr:predicateObjectMap [
        rr:predicate :worksIn ;
        rr:objectMap [
            rr:template "https://example.org/Department/{dept_id}"
        ]
    ] .

OntoBricks Components:

  • R2RMLGenerator (src/back/core/w3c/r2rml/R2RMLGenerator.py) - Generates R2RML from mapping config
  • R2RMLParser (src/back/core/w3c/r2rml/R2RMLParser.py) - Parses existing R2RML files

4. SPARQL (SPARQL Protocol and RDF Query Language)

What it is: The standard query language for RDF data, similar to SQL for relational databases.

How OntoBricks uses it:

  • SPARQL is used internally to generate Spark SQL from R2RML mappings
  • Users do not write SPARQL directly — the system handles translation automatically
  • The external REST API (/api/v1/query) also accepts SPARQL for programmatic access

SPARQL Query Example:

PREFIX ont: <https://example.org/ontology#>
SELECT ?person ?personName ?department
WHERE {
    ?person a ont:Person .
    ?person rdfs:label ?personName .
    ?person ont:worksIn ?department .
}
LIMIT 100

OntoBricks SPARQL-to-SQL Translation:

  • SparqlTranslator (src/back/core/w3c/sparql/SparqlTranslator.py) implements the translator
  • SparqlCapabilityValidator (src/back/core/w3c/sparql/SparqlCapabilityValidator.py) enforces a fail-closed Spark subset before SQL generation
  • Parses SPARQL patterns (subject, predicate, object)
  • Maps patterns to table columns using R2RML mappings
  • Generates Spark SQL with JOINs, UNION ALL, and STACK functions
  • Supported Spark subset: SELECT/SELECT *, DISTINCT, LIMIT, basic graph patterns, OPTIONAL on supported patterns, string FILTER (CONTAINS, string equality, STRSTARTS, STRENDS), predicate IN, literal BIND, and the specialized relationship UNION shape
  • Rejected by design: GROUP BY, HAVING, ORDER BY, OFFSET, numeric/complex filters, property paths, subqueries, MINUS, VALUES, SERVICE, GRAPH, arbitrary UNION, and non-literal BIND
  • The local RDFLib path is not a warehouse-data fallback: it operates on mapping graphs, not Databricks source data

5. Query Processing Pipeline (inspired by SANSA)

What it is: OntoBricks translates ontology mappings into SQL queries to extract triples from Databricks tables and materialize them into a Delta view in Unity Catalog and into the domain's configured Graph DB engine (Lakebase Postgres, Unity Catalog Delta, or Neo4j).

How OntoBricks implements this (inspired by the SANSA Stack):

OBDA Query Flow

Processing Steps:

  1. SPARQL Query - Generated internally from ontology and mappings
  2. SPARQL Parser - Extract SELECT variables, parse WHERE patterns
  3. Triple Patterns - Identify (subject, predicate, object) patterns
  4. R2RML Analyzer - Load TriplesMap definitions, build mappings
  5. SPARQL→SQL Translator - Match patterns to mappings, generate SQL
  6. Generated Spark SQL - Query with JOINs and UNION ALL
  7. Triple Store Backend Dispatch - The single GraphDBFactory returns the active engine — a Delta-backed store (DeltaFlatStore) or the Lakebase engine (LakebaseFlatStore). Both subclass GraphDBBackend and expose the same (subject, predicate, object) contract.
  8. RDF-style Results - Uniform (subject, predicate, object) triples from both backends
  9. Graph Viewer - Sigma.js WebGL-powered graph with entity details panel, search, filtering, and data cluster detection (Louvain/Label Propagation/Greedy Modularity)

Generated Spark SQL Example (for generic triple query):

SELECT DISTINCT subject, predicate, object FROM (
    -- Entity triples (rdf:type and properties)
    SELECT 
        CONCAT('https://example.org/Person/', CAST(person_id AS STRING)) AS subject,
        stack(2, 
            'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', 'https://example.org/ontology#Person',
            'http://www.w3.org/2000/01/rdf-schema#label', CAST(name AS STRING)
        ) AS (predicate, object)
    FROM main.default.person

    UNION ALL

    -- Relationship triples
    SELECT 
        CONCAT('https://example.org/Person/', CAST(person_id AS STRING)) AS subject,
        'https://example.org/ontology#worksIn' AS predicate,
        CONCAT('https://example.org/Department/', CAST(dept_id AS STRING)) AS object
    FROM (SELECT person_id, dept_id FROM main.default.person_department) AS rel_subquery
) AS triples
WHERE object IS NOT NULL
LIMIT 100

Application Architecture

The application follows a clean Routes → Domain objects → Core layered architecture. The FastAPI surface is split across shared, front, and back packages (see FastAPI application split below). The stateless external REST API lives under src/api/ and is mounted by the shared app factory.

Layered Design

Layer Components Responsibility
Routes HTML: src/front/routes/*.py; session-aware JSON: src/api/routers/internal/*.py Thin HTTP handlers (request/response only)
Domain Objects Classes in src/back/objects/ Business logic, validation, transformation (routes call domain classes directly)
Core back/core/helpers/, DatabricksClient, VolumeFileService, OWL/R2RML generators, triple-store factory, GlobalConfigService, PermissionService, BuildScheduler Shared utilities, Databricks connectivity, backend abstraction
Services src/back/services/ (e.g. home.py) Page-level orchestration where routes delegate beyond raw domain objects
Frontend OntoViz, Sigma.js, Graphology, D3.js, Bootstrap; src/front/templates/, src/front/static/ Visual design, graph rendering, UI

FastAPI application split

The ASGI app is built in src/shared/fastapi/main.py (create_app()), which wires middleware, static files, and routers. Responsibilities are divided as follows:

Package Location Role
shared shared/fastapi/main.py, shared/fastapi/health.py, shared/fastapi/csrf.py, shared/fastapi/timing.py Application factory, CORS / session / permission / CSRF / request-timing middleware, /static mount, health and root endpoints; includes routers from front.routes, api.routers.internal, and mounts the external API
front front/fastapi/dependencies.py Jinja2 templates and shared FastAPI/Starlette dependencies for HTML routes
back back/fastapi/graphql_routes.py GraphQL router (per-domain auto-generated schema)

Uvicorn entry point: shared.fastapi.main:app (see run.py, which imports create_app() from shared.fastapi.main).

Configuration Split

OntoBricks separates configuration into several layers:

File Purpose Examples
src/shared/config/settings.py Environment-specific settings loaded from .env / env vars via Pydantic BaseSettings Databricks host, token, session directory
src/shared/config/constants.py Static constants and defaults that rarely change and are shared across modules App name/version, OWL namespaces, LLM defaults, wizard quick-templates
src/front/config/menu_config.json Navbar + sidebar navigation for the Jinja2 UI Page labels, Bootstrap Icons (icon), menu structure; top-level icons must stay distinct (Registry bi-boxes, Domain bi-box, Ontology bi-bezier2, Mapping bi-shuffle, Knowledge Graph bi-radar) and match breadcrumb.js _ROUTE_MAP
src/back/objects/session/GlobalConfigService.py Instance-level GlobalConfigService — admin-editable settings stored in the registry (global_config JSONB, or .global_config.json on Volume-backed registries), shared across all user sessions SQL Warehouse ID, default base URI, default class icon, UI branding (ui_branding)
src/back/objects/registry/PermissionService.py PermissionService — stores per-user permission levels in .permissions.json (app-wide) and per-domain overrides in .domain_permissions.json (per domain folder). Defines the role hierarchy: admin > builder > editor > viewer > none. CAN MANAGE admin flag

src/shared/config/constants.py key contents:

Constant Description
APP_NAME, APP_VERSION Application identity
ONTOBRICKS_NS RDFLib Namespace for the OntoBricks schema (http://ontobricks.com/schema#)
DEFAULT_BASE_URI Default ontology base URI
LLM_DEFAULT_MAX_TOKENS, LLM_DEFAULT_TEMPERATURE LLM generation defaults
WIZARD_TEMPLATES Ontology generation quick-templates (served to the frontend via GET /ontology/wizard/templates)
AUTO_ASSIGN_CHUNK_SIZE Max entities + relationships per auto-map agent run (default: 5)
AUTO_ASSIGN_CHUNK_COOLDOWN Seconds to wait between agent chunks to avoid LLM rate limits (default: 15)

To add a new generation template, add an entry to WIZARD_TEMPLATES in src/shared/config/constants.py — the UI button is rendered dynamically.

src/back/objects/session/GlobalConfigService.py (GlobalConfigService singleton):

Setting Description Modified By
warehouse_id Build SQL Warehouse ID used for mapping views, DDL, and materialization Admin only
warehouse_use_sea Legacy compatibility key; always persisted and resolved as false because build SQL uses Thrift Internal compatibility only
use_cloud_fetch Whether SQL clients download result files via CloudFetch (default on) Admin only
graph_engine_config.lakehouse.warehouse_id Optional Lakehouse query warehouse, including Lakehouse//RT Admin only
graph_engine_config.lakehouse.use_sea Selects the SEA transport required for Lakehouse//RT: direct INLINE requests in Apps, Kernel locally Admin only
default_base_uri Default ontology base URI domain Admin only
default_emoji Default class icon emoji (e.g. 📦) Admin only
ui_branding Versioned object: app_title, primary_color, logo_data_url (empty = bundled favicon) Admin only (GET/POST /settings/ui-branding)

Without an RT query override, resolve_delta_warehouse_id() intentionally falls back to the Build SQL Warehouse. The Settings UI represents this by disabling Query and mirroring Build. RT mode requires a distinct query warehouse; disabling it persists an empty Lakehouse warehouse ID. In Databricks Apps, RT reads bypass the SQL connector's Kernel adapter and use Statement Execution directly with JSON_ARRAY / INLINE. Internal chunk links stay on the workspace host, external CloudFetch links are rejected, and a truncated 24 MiB response fails explicitly. Local RT reads retain Kernel; builds and graph-index refreshes retain the Build warehouse over Thrift.

The service caches the document in memory with a TTL. Persistence goes through the active RegistryStore (save_global_config / load_global_config), so Lakebase and Volume backends keep the same keys. Settings are resolved via resolve_warehouse_id(), resolve_default_base_uri(), and resolve_default_emoji() in src/back/core/helpers/. UI branding is normalized by normalize_ui_branding() (src/back/core/helpers/UIBranding.py) and injected per HTML request by UIBrandingMiddleware. Version-scoped UC paths are derived through effective_uc_version_path in DatabricksHelpers.py.

UC Volume file layout (root of the configured registry volume):

/Volumes/{catalog}/{schema}/{volume}/
├── .registry                  # Marker file (presence = initialized)
├── .global_config.json        # Instance-level admin settings (includes build schedules)
├── .permissions.json          # App-wide per-user permission levels (viewer / editor / builder)
└── domains/                   # Domain version files (legacy registries may use `projects/`)
    └── {domain_name}/
        ├── .domain_permissions.json  # Optional per-domain role overrides
        ├── V1/
        │   └── V1.json                                    # Domain version payload
        ├── V2/
        │   └── V2.json
        └── ...

Knowledge Store documents. Uploaded documents are not stored on the Volume. As of v0.9.0 they are parsed on upload and only the parsed text is persisted in the Lakebase domain_documents table (the original binary is never retained). See Registry Storage.

Key Design Principles

  1. Separation of Concerns: Routes handle HTTP, services handle logic
  2. Session State: Custom file-based session stores ontology, mappings, R2RML between requests
  3. Modular UI: Sidebar layout with reusable partials per page
  4. No Manual Query Writing: SPARQL is used internally — translated to SQL automatically for triple materialization
  5. Visual-First Design: OntoViz enables drag-and-drop ontology creation
  6. Agentic Automation: LLM-powered agents with MCP-style tools handle complex tasks autonomously (see Agentic Architecture)
  7. Observability: MLflow tracing captures every agent → LLM → tool span for debugging, cost tracking, and evaluation
  8. MCP Integration: The MCP server exposes knowledge-graph tools (entity search, GraphQL queries, domain selection) to LLM clients via the Model Context Protocol (see MCP Server)

DocumentParseService owns the Knowledge Store document lifecycle, backed by the Lakebase domain_documents table (parsed text only — the original binary is never persisted). Uploads are tracked per row with a source_hash and a pending, ready, or failed status. Supported files are parsed asynchronously through ai_parse_document (inline base64, see below); the parsed text is written before the row becomes ready. There is a hard 10 MB per-file upload cap (base64 inflation against the Statement Execution API's ~16 MiB limit). Generate and Mapping are read-only corpus consumers and never invoke the extractor. Creating a new version copies the parsed-text rows.


Module Structure

The application follows a strict code organization pattern (see src/.coding_rules.md):

  • Routes — HTML handlers live in src/front/routes/; session-aware JSON endpoints live in src/api/routers/internal/. Keep routing thin (no business rules or data access in route functions).
  • Domain objects (back.objects) hold business logic; routes call them directly unless they use a small service in src/back/services/.
  • Core (back.core) holds reusable infrastructure, Databricks connectivity, and W3C standards.
  • Front — Jinja2 templates are consolidated under src/front/templates/; static assets under src/front/static/; menu config under src/front/config/.
  • Shared — App factory, health routes, and cross-cutting settings/constants (shared.config).
  • All Python files in core/ and objects/ use PascalCase naming (e.g. DatabricksClient.py).
src/
├── shared/                             # Shared app shell & configuration
│   ├── fastapi/
│   │   ├── main.py                     # Application factory (create_app), middleware, router registration
│   │   ├── health.py                   # Health check & root endpoints
│   │   ├── csrf.py                     # CSRF double-submit cookie middleware
│   │   └── timing.py                   # Request duration logging middleware
│   └── config/
│       ├── settings.py                 # Pydantic BaseSettings (env vars, .env)
│       └── constants.py                # Static constants & defaults (namespaces, LLM params, wizard templates)
│
├── front/                              # HTML UI: routes, templates, static, menu
│   ├── fastapi/
│   │   └── dependencies.py             # Jinja2 templates & shared dependencies for HTML routes
│   ├── config/
│   │   └── menu_config.json            # Sidebar navigation structure
│   ├── routes/                         # HTML page routers (home, ontology, mapping, graph viewer, project)
│   ├── templates/                      # Consolidated Jinja2 templates (partials per feature area)
│   └── static/                         # Static assets (css/, js/, img/, ontoviz/, per-area folders)
│
├── back/                               # Backend: domain, core infra, GraphQL
│   ├── fastapi/
│   │   └── graphql_routes.py           # GraphQL API (auto-generated schema per domain)
│   ├── services/                       # Optional page-level services (e.g. home.py)
│   ├── core/                           # Core infrastructure
│   │   ├── helpers/                    # Centralized helper functions
│   │   │   ├── DatabricksHelpers.py
│   │   │   ├── SQLHelpers.py
│   │   │   └── URIHelpers.py
│   │   ├── logging/                    # Centralized logging (dictConfig via LogManager)
│   │   │   └── LogManager.py
│   │   ├── task_manager/               # In-memory async task runner (threading-based)
│   │   │   └── TaskManager.py
│   │   ├── errors/                     # Centralized error hierarchy
│   │   │   ├── OntoBricksError.py      # Base error class
│   │   │   ├── ValidationError.py
│   │   │   ├── NotFoundError.py
│   │   │   ├── AuthorizationError.py
│   │   │   ├── ConflictError.py
│   │   │   ├── InfrastructureError.py
│   │   │   └── ErrorResponse.py
│   │   │
│   │   ├── databricks/                 # Databricks connectivity
│   │   │   ├── DatabricksAuth.py       # Authentication & utility functions
│   │   │   ├── DatabricksClient.py     # Thin facade
│   │   │   ├── SQLWarehouse.py         # Query execution, DDL (connection-pooled)
│   │   │   ├── StatementExecutionWarehouse.py # Apps RT reads with INLINE SEA
│   │   │   ├── unity_catalog/          # Unity Catalog metadata, volumes, domain I/O
│   │   │   │   ├── UnityCatalog.py     # Catalogs, schemas, tables, volumes
│   │   │   │   ├── VolumeFileService.py # File I/O on UC Volumes
│   │   │   │   ├── UCDomainIO.py       # Domain I/O on UC Volumes
│   │   │   │   └── MetadataService.py  # Table metadata
│   │   │   ├── WorkspaceService.py     # SCIM users/groups
│   │   │   ├── DashboardService.py     # Lakeview + legacy dashboards
│   │   │
│   │   ├── w3c/                        # W3C semantic web standards
│   │   │   ├── owl/                    # OntologyGenerator, OntologyParser
│   │   │   ├── r2rml/                  # R2RMLGenerator, R2RMLParser
│   │   │   ├── rdfs/                   # RDFSParser
│   │   │   ├── sparql/                 # SparqlTranslator, SparqlQueryRunner, DomainQueryService
│   │   │   └── shacl/                  # SHACLGenerator, SHACLParser, SHACLService
│   │   │
│   │   ├── graphql/                    # GraphQLSchemaBuilder, ResolverFactory, SchemaMetadata
│   │   ├── graphdb/                    # Single triple store / graph DB abstraction
│   │   │   ├── GraphDBBackend.py       # Abstract base (CRUD + named queries + graph ops)
│   │   │   ├── GraphDBFactory.py       # Engine factory (auto / lakebase / delta / view)
│   │   │   ├── constants.py            # RDF_TYPE, RDFS_LABEL
│   │   │   ├── delta/                  # DeltaFlatStore (SQL Warehouse engine)
│   │   │   ├── lakebase/               # LakebaseFlatStore, LakebaseBase, SyncedTableManager
│   │   │   └── _starter_kit/           # ExampleStore template for new engines
│   │   │
│   │   ├── reasoning/                  # Reasoning engine (OWL 2 RL + SWRL + SPARQL rules + Decision tables)
│   │   │   ├── ReasoningService.py     # Multi-phase orchestrator
│   │   │   ├── OWLRLReasoner.py        # OWL 2 RL deductive closure via owlrl
│   │   │   ├── swrl/                   # SWRLEngine, SWRLParser, SWRLSQLTranslator, SWRLFlatCypherTranslator,
│   │   │   │                           # SWRLBuiltinRegistry, SWRLBuiltin, SWRLAtomPartition, SWRLTextCodec
│   │   │   ├── rules/                  # SPARQLRuleEngine, AggregateRuleEngine, DecisionTableEngine
│   │   │   └── results/                # InferredTriple, RuleViolation, ReasoningResult
│   │   │
│   │   ├── industry/                   # Industry-standard ontology importers
│   │   │   ├── fibo/                   # FiboImportService
│   │   │   ├── cdisc/                  # CdiscImportService
│   │   │   └── iof/                    # IofImportService
│   │   │
│   │   ├── graph_analysis/             # Community detection & clustering
│   │   │   ├── CommunityDetector.py    # CommunityDetector (NetworkX backend)
│   │   │   └── models.py              # ClusterRequest, ClusterResult, DetectionResult, DetectionStats
│   │   │
│   │   ├── github/                     # GitHub Git Data API client (no git clone)
│   │   │   └── GitHubClient.py         # Atomic tree commits for the registry mirror
│   │   │
│   │   └── sqlwizard/                  # SQL generation helpers for entity mapping
│   │       └── SQLWizardService.py
│   │
│   └── objects/                        # Domain objects (business logic layer)
│       ├── ontology/                   # Ontology domain (Ontology*.py, json_views.py)
│       │   └── generate/               # GenerateWorkflow, GenerateDraft(+Store), draft errors
│       ├── mapping/                    # Mapping domain (mapping.py, json_views.py)
│       ├── domain/                     # Saved domain / UC I/O (Domain.py, payload.py, version_status.py)
│       │   └── settings/               # SettingsService + *Settings value objects
│       │       └── graphengine/        # GraphEngineSettings (+ Neo4j / Lakebase)
│       ├── digitaltwin/                # Knowledge Graph domain (DigitalTwin.py, Twin*.py, models.py)
│       │   ├── build/                  # Graph build pipeline, lakehouse build, inferred materialisation
│       │   ├── quality/                # SQL quality checks and data-quality runs
│       │   ├── cohort/                 # CohortService, CohortEngineContext
│       │   ├── explorer/               # GraphFilter, GraphFind, neighbours, ontology groups
│       │   ├── node/                   # Node context, business rules, virtual attributes
│       │   ├── query/                  # TwinMapping, TwinSparqlTranslate
│       │   └── cache/                  # TwinStoreCache, TwinAssistantCache
│       ├── session/                    # Session management
│       │   ├── middleware.py           # File-based session middleware (cookie + ASGI)
│       │   ├── SessionManager.py       # Request-scoped session get/set/delete wrapper
│       │   ├── DomainSession.py       # DomainSession (current OntoBricks domain payload)
│       │   └── GlobalConfigService.py  # Instance-level GlobalConfigService
│               └── registry/                   # Registry, permissions & scheduled builds
│           ├── RegistryService.py      # RegistryService + RegistryCfg at root
│           ├── PermissionService.py    # roles and domain-level overrides
│           ├── collab/                 # CommentService, ReviewService, EditLockService
│           ├── schedule/               # BuildScheduler + task-type specs
│           ├── gitsync/                # GitHubConfig, GitHubSyncService, GitHubMirror(+Hooks)
│           └── store/                  # RegistryStore ABC + Lakebase mixins (GitHubMirrorHooks)
│
├── api/                                # REST API layer (mounted into the main app)
│   ├── external_app.py                 # External stateless API app factory (/api/v1/…)
│   ├── service.py                      # API business logic
│   └── routers/
│       ├── v1.py                       # /api/v1/* endpoints
│       ├── domains.py                  # Domain registry & artifact endpoints (`/api/v1/domains`, `/api/v1/domain/...`)
│       ├── digitaltwin.py              # Knowledge Graph REST API
│       └── internal/                   # Session-aware JSON routes for the web UI
│           ├── home.py, settings.py, domain.py, ontology.py, mapping.py, dtwin.py, tasks.py, …
│
├── agents/                             # LLM Agents
│   ├── llm_utils.py                    # Shared LLM call with retry (429/503 backoff)
│   ├── serialization.py                # Agent serialization utilities
│   ├── tracing.py                      # MLflow tracing setup & decorators
│   ├── tools/                          # Shared agent tools (ontology, mapping, metadata, SQL, etc.)
│   ├── agent_owl_generator/            # OWL ontology generation agent
│   ├── agent_auto_assignment/          # Entity/relationship → SQL mapping agent
│   ├── agent_auto_icon_assign/         # Emoji icon mapping agent
│   └── agent_ontology_assistant/       # Conversational assistant + ResponsesAgent wrapper
│
└── mcp-server/                         # MCP Server (separate Databricks App; under src/)
    ├── app.yaml                        # Databricks App config (also rendered via DAB)
    ├── deploy-mcp-server.sh            # Legacy standalone deploy (prefer `make deploy`)
    ├── pyproject.toml                  # Python dependencies
    └── server/
        ├── app.py                      # MCP tools, domain selection, text formatting
        └── main.py                     # Entry point

tests/                                  # Test suite (at project root)
├── conftest.py
├── e2e/                                # End-to-end tests
│   └── test_e2e_flows.py
├── test_lakebase_flat_store.py
├── test_synced_table_manager.py
├── test_reasoning.py
├── test_reasoning_service.py
├── test_permissions.py
├── test_registry.py
├── test_triplestore_factory.py
├── test_graphql.py
├── test_sparql_service.py
├── test_owl_generator.py
├── test_owl_parser.py
├── test_r2rml_generator.py
├── test_r2rml_parser.py
├── ... (50+ test modules)

OntoViz Component Architecture

OntoViz is a custom JavaScript library for visual entity-relationship diagram editing. It is designed to be reusable and can be integrated into other projects.

For complete documentation, see OntoViz Documentation.

Key Features

Feature Description
Entities OWL Classes with icons, names, and data properties
Relationships OWL Object Properties with direction and attributes
Inheritances rdfs:subClassOf links with property inheritance
Canvas Controls Zoom, pan, auto-layout, minimap
Serialization JSON export/import for persistence

Core Classes

class Entity {
    id, name, icon, description, properties, x, y
}

class Relationship {
    id, name, sourceEntityId, targetEntityId, direction, properties
}

class Inheritance {
    id, sourceEntityId, targetEntityId
}

class OntoViz {
    // Entity, Relationship, Inheritance management
    // Layout & navigation
    // JSON serialization
}

Inheritance Feature

Inheritance links represent rdfs:subClassOf relationships in OWL:

  • Visual representation: Dotted line with hollow arrow from parent to child
  • Drag-and-drop creation: Click △ toolbar button, then drag from parent connector to child entity
  • Property inheritance: Child entities automatically inherit and display parent's properties (read-only)
  • OWL generation: Produces rdfs:subClassOf triples in the generated OWL
  • Cascade updates: When parent properties change, child entities are automatically updated

User Interface Architecture

The UI uses a consistent sidebar layout across all main pages:

UI Layout

UI Components

Component File Purpose
Base Template base.html Navbar, global CSS/JS
Sidebar Layout sidebar-layout.css Reusable sidebar + content structure
Sidebar Nav sidebar-nav.js Tab-like navigation controller
Partials partials/_*.html Section content (information, entities, etc.)
Core JS ontology-core.js, mapping-core.js Shared state and functions
OntoViz ontoviz.js, ontoviz.css Visual ontology designer
  • L1 (global utilities): icon-only Registry launcher plus warehouse status, task tracker, notification center, help, and user menu.
  • L2 (domain context rail): domain identity target (#domainContextTrigger), the four-workspace segmented rail (Domain, Ontology, Mapping, Knowledge Graph), inline breadcrumb, and Versions -> Close -> Save actions.
  • Settings override in same L2 slot: when body[data-page="settings"] and a domain is loaded, #obSubnav swaps to a single return control (#settingsDomainReturnLink) under #settingsDomainReturnNav; the regular rail (#domainWorkspaceSubnavNav), domain identity, breadcrumb, and actions are hidden.
  • Workspace map: clicking #domainContextTrigger opens #workspaceMapModal (menu-driven four-column map). The same handler is bound to #settingsDomainReturnLink; its fallback href is /domain/ when JavaScript is unavailable.
  • Unloaded session: Domain, Ontology, Mapping, and Knowledge Graph HTML routes (front/routes/{domain,ontology,mapping,dtwin}.py) 303-redirect to / when WorkspacePresence.is_loaded() is false, matching domainIsLoaded in navbar.js. Home, Settings, and About do not require a domain.
  • Active workspace: navbar.js marks the current workspace as a static aria-current="page" segment and removes its dropdown wiring; inactive segments keep their Bootstrap dropdown menus.
  • Responsive behavior: below 768px, labels are visually hidden and the rail uses titled icon targets while preserving DOM labels for accessibility.

Ontology Studio multi-select

The Studio D3 canvas (src/front/static/ontology/js/ontology-map.js) keeps one module-level selection set, mapSelectedEntityNames. Every write goes through _setMapSelection(names, options), which syncs the .map-node.selected ring, runs 1-hop neighbourhood dimming only when exactly one entity is selected, guarded-closes the single-entity panel otherwise, and closes any open context menu (a menu captures the selection it was opened for).

Gesture Behaviour
Toolbar Select toggle While on, a click toggles membership (panel stays closed) and a primary-button drag on empty canvas marquees; pan is disabled except for wheel zoom. Ctrl/Cmd still works when the toggle is off
Ctrl/Cmd-click on an entity Toggle membership; the panel does not open
Ctrl/Cmd-drag on empty canvas Marquee; on pointerup the selection is replaced by the entities inside. An empty marquee leaves the selection unchanged
Plain click on entity / empty canvas Select one entity (opens panel) / clear selection
Escape Close the context menu and clear a multi-selection. Ignored while a Bootstrap modal is open or Studio (#map-section) is not the active section

Design notes:

  • Click after marquee. A browser dispatches click on the canvas right after the marquee pointerup. _suppressNextMapCanvasClick() arms a one-shot, time-boxed guard (reset by the next pointerdown) that the canvas click handler consumes first, so the marquee result survives.
  • Marquee lifecycle. pointermove / pointerup / pointercancel / blur / canvas pointerleave listeners are attached per gesture and removed by cleanup(), which never changes the selection. Releasing Ctrl/Cmd before pointerup cancels the marquee.
  • macOS Control-click. Control-click raises contextmenu rather than click, so the node contextmenu handler toggles membership when a modifier is held (and the canvas contextmenu handler ignores modifier events).
  • Group actions. Dragging a selected node moves the whole set by the same delta; the multi-select menu offers Create Business View and Delete N entities and re-reads the live selection when clicked.
  • Map rebuilds. initOntologyMap() resets the selection with { closePanel: false } so a rebuild never double-saves or closes a panel that was just opened.
  • Business Views. createBusinessViewFromEntity() (1-hop) and createBusinessViewFromSelection() (selected-only, Auto_Selection) only collect names and links; both delegate view creation, layout, visibility and navigation to _createMapBusinessView().

Regression coverage: tests/units/front/test_ontology_map_multi_select.py (source contracts) and tests/e2e/ontology/test_studio_multi_select_flows.py (real Playwright pointer input).

Inherited outgoing relations

Object properties are not copied onto subclasses. ClassModel.outgoing_relations_for_class and the JS helper outgoingRelationsForClass walk parent at read time and return own + inherited outgoing relations (inherited, inheritedFrom = the declaring ancestor). Studio and Mapping graphs draw dashed subclass→range edges; the entity panel lists them read-only. OWL export and R2RML keep a single rdfs:domain on the declaring class. Incoming (range) inheritance is out of scope.

Page Structure

Each main page (Ontology, Mapping, Knowledge Graph) follows this pattern:

page.html
├── sidebar-layout (container)
│   ├── sidebar-nav (left menu)
│   │   ├── Section group 1
│   │   │   └── Nav links (data-section="...")
│   │   └── Section group 2
│   │       └── Nav links
│   └── sidebar-content (right area)
│       ├── section#design-section
│       │   └── {% include "partials/_ontology_design.html" %}
│       ├── section#entities-section
│       │   └── {% include "partials/_ontology_entities.html" %}
│       └── ... more sections
└── page-specific scripts

Data Flow

Data Flow

Flow Summary

Flow Steps Key Components
Design Visual design → Auto-save → Session storage OntoViz, Session middleware
Ontology Design/Configure → Save → Generate OWL OntologyGenerator, Session middleware
Mapping Load ontology → Map/Auto-Map → Validate attributes → Generate R2RML R2RMLGenerator, SQLWizardService, TaskManager
Knowledge Graph Build → Quality Check (async) → Auto-load Triples → Explore Graph Viewer sparql_service, TaskManager, Sigma.js graph
API/MCP REST → resolve domain → triple store query → formatted response Knowledge Graph API, MCP Server, GraphQL

Asynchronous Task Processing

Long-running operations use the TaskManager pattern (src/back/core/task_manager/TaskManager.py), an in-memory singleton that manages background tasks:

Task Type Triggered By Description
triplestore_sync Knowledge Graph → Build Generates and writes triples to Delta and the domain's configured Graph DB engine (Lakebase, Delta, or Neo4j)
quality_checks Knowledge Graph → Quality Runs all quality checks sequentially with per-check progress
auto_assign Mapping → Auto-Map Batch-maps entities and relationships via LLM; splits large jobs into chunks of AUTO_ASSIGN_CHUNK_SIZE with cooldown between chunks to avoid rate limits

How it works:

  1. Frontend sends a POST to start the task; backend creates a TaskManager task and spawns a threading.Thread
  2. Frontend stores the task_id in sessionStorage and polls /tasks/{task_id} for progress
  3. Backend thread updates progress (percentage, current step message) via TaskManager
  4. On completion, the task result is returned to the frontend, which saves mappings and updates the UI
  5. If the user navigates away and returns, the frontend resumes monitoring from sessionStorage

Scheduled Builds (BuildScheduler)

The BuildScheduler (src/back/objects/registry/schedule/BuildScheduler.py) provides per-domain scheduled triple store builds using APScheduler's BackgroundScheduler. Schedule definitions are persisted in .global_config.json on the UC Volume alongside other instance-level settings.

Each schedule entry contains:

Field Description
interval_minutes How often to run (2, 5, 10, 30, 60, 360, 720, 1440)
drop_existing Whether to replace data on each build
enabled Whether the schedule is active
last_run ISO timestamp of the last execution
last_status "success" / "error" / null
last_message Human-readable outcome of the last run

Jobs are restored at startup from environment-variable credentials when available. If registry config is session-only, jobs are lazily registered when a user opens the Schedule tab.

Session State

The session middleware maintains state using a unified domain session pattern (implemented by DomainSession):

Key Contents Set By
project_data Complete domain: info, ontology, mapping, design_layout, databricks, preferences, generated DomainSession

Unified Session Structure:

{
    "info": { "name", "description", "author" },
    "current_version": "1.0",
    "ontology": { 
        "name", "base_uri", "classes", "properties",
        "constraints", "swrl_rules", "axioms" 
    },
    "assignment": { 
        "entities", "relationships", 
        "r2rml_output"  # Runtime only, not exported
    },
    "design_layout": { "entities", "relationships", "inheritances", "positions" },
    "databricks": { "host", "token" },  # Not exported; warehouse_id is in GlobalConfigService
    "preferences": { },                 # Not exported; emoji/base URI are in GlobalConfigService
    "generated": { "owl", "sql" }       # Not exported
}

Session Service Pattern:

The DomainSession class (src/back/objects/session/DomainSession.py) provides:

  • Unified access to all domain data
  • Automatic migration from legacy session keys
  • Export/import for file persistence
  • Version management support

Registry Storage

Since v0.4.0 the domain registry lives in Databricks Lakebase (Postgres). The historical JSON-on-Volume backend was removed — operators with pre-v0.4.0 deployments must run scripts/migrations/migrate-registry-to-lakebase.sh once before upgrading. Uploaded Knowledge Store documents also live in Lakebase (parsed text in domain_documents); the Unity Catalog Volume is now reserved only for ad-hoc registry export bundles (OWL import / R2RML export use arbitrary user-chosen volumes). An optional GitHub repository can mirror the same registry documents for review and restore — see GitHub repository mirror.

Storage Identifier What lives in it
Databricks Lakebase (Postgres) lakebase Domain JSON, permissions, schedules, history, global config, and Knowledge Store parsed documents (domain_documents) — normalised into relational tables (with JSONB columns for the larger blobs)
Unity Catalog Volume n/a Ad-hoc registry export bundles (no document uploads)
GitHub repository (optional) github_config Reviewable commits of domain/version JSON + generated Turtle; not a second source of truth

The single :class:RegistryStore implementation (LakebaseRegistryStore) is constructed via RegistryFactory.from_cfg. Route handlers and services talk to the abstract interface and stay storage-agnostic.

Volume layout (export bundles only)

Unity Catalog
└── catalog (e.g., main)
    └── schema (e.g., ontobricks)
        └── volume (e.g., OntoBricksRegistry)
            └── (ad-hoc registry export bundles)

Uploaded documents are no longer written to the Volume — they are parsed on upload and stored as text in the Lakebase domain_documents table.

Lakebase layout

The Postgres schema (default ontobricks_registry) holds sixteen relational tables:

Table Purpose
registries One row per (catalog, schema, volume) triplet — scopes everything else
global_config Instance-wide settings (warehouse, emoji, base URI, ui_branding, …) as JSONB
domains Stable per-domain identity (UUID, name, base URI, description) plus mcp_policy — a JSONB blob holding the per-domain MCP policy (which tools the domain publishes, how its ontology attachments are surfaced). Defaults to {}, which reproduces pre-0.8 behaviour, so no backfill is needed
domain_versions Per-version JSONB document; mirrors what V{N}.json used to hold
domain_documents Knowledge Store parsed documents (filename, version, status, parsed_text, source_hash); stores parsed text only — no original binary. FK-cascades on domain delete; version copy carries the parsed text
domain_permissions Per-domain ACL (replaces .domain_permissions.json)
domain_edit_locks Advisory per-domain edit locks for collaborative editing
schedules Active scheduled-build configuration
schedule_runs Ring-buffered run history per domain
build_runs Append-only build-run trace (all paths) keyed by (domain_id, version) for analytics; active build = latest successful run
graph_analytics Cache of the LAST knowledge-graph metrics result (centrality/structure) keyed by (domain_id, version); one row, replaced on every successful async recompute (UPSERT). Backs the KG Analytics page and the Domain Validation cockpit
graph_analytics_runs Append-only history of every analytics run launched (success or failure) keyed by (domain_id, version); lightweight per-run metadata (node/edge counts, components, avg degree, density, duration, scope, status). Capped per tuple. Backs the KG Analytics "History" tab
domain_review_events Append-only review/validation audit log (submit / sign-off / publish / reopen / comment) keyed by (domain_id, version)
domain_change_events Append-only ontology/mapping change audit ("who changed what, and when") keyed by (domain_id, version). Fine-grained edits (class/property/mapping add/update/remove, SHACL/SWRL/groups/axioms/expressions/business rules, imports, resets) are buffered in the working session as they happen and flushed here in one batch on save-to-registry; source tags human vs AI-assistant edits; occurred_at is the real edit time, created_at the flush time
domain_comments Domain-wide threaded discussion keyed by (domain_id, version); parent_id links replies, resolved closes a thread
domain_tasks Personalised work items assigned to a teammate (usually born from a comment); status walks open → in_progress → done (or cancelled), surfaced in the assignee's "My Tasks" worklist

Authentication is fully app-managed: the Databricks Apps runtime injects PGHOST/PGPORT/PGDATABASE/PGUSER and OntoBricks mints a short-lived OAuth token via WorkspaceClient().config.authenticate() (back/core/databricks/LakebaseAuth.py). No user secrets are stored. OntoBricks targets Lakebase Autoscaling exclusively (the default tier since 2026-03-12); Provisioned instances are not supported. The connection layer retries on SQLSTATE 57P03 to absorb scale-from-zero cold-starts.

Ad-hoc registry export bundles continue to live on the Unity Catalog Volume above, managed by VolumeFileService. Uploaded Knowledge Store documents are not written to the Volume — they are parsed on upload and stored as text in domain_documents.

Export Format (Versioned)

Domains are exported in a versioned JSON format:

{
    "info": { 
        "name": "My Domain", 
        "description": "...", 
        "author": "...",
        "mcp_policy": { /* per-domain MCP tool + context policy; {} when unconfigured */ }
    },
    "versions": {
        "1": {
            "ontology": { /* classes, properties, constraints, rules, axioms */ },
            "assignment": { /* entity and relationship mappings */ },
            "design_layout": { /* OntoViz visual state */ }
        }
    }
}

info also carries the domain-level flags the registry needs to serve the domain: mcp_enabled, status, review_quorum, graph_backend, lakehouse_materialization and mcp_policy. The policy is re-validated on both export and import, so a hand-edited or older bundle can never inject an unknown tool name — unrecognised entries are dropped rather than rejected.

What is NOT Saved

For security and regeneration reasons, these are excluded from exports:

  • Databricks credentials (host, token)
  • Instance-level settings (warehouse_id, base URI, emoji — stored in GlobalConfigService)
  • R2RML output (regenerated from mappings on load)
  • OWL output (regenerated from ontology on load)
  • Query results (ephemeral data)
  • User preferences (runtime only)
  • GitHub tokens (resolved live from a Databricks secret or ONTOBRICKS_GITHUB_TOKEN; never written to the repository)

GitHub repository mirror

Administrators configure one GitHub repository per OntoBricks instance under Settings → Configuration → GitHub. Lakebase remains canonical. The mirror is a reviewable git history plus generated Turtle next to the JSON sources.

Write path. GitHubMirrorHooks mixes into the registry store. After a successful write_version / status change / version delete, GitHubMirror queues a job and a daemon worker waits DEBOUNCE_S (2 s) so a burst of saves becomes one commit. Deleting a whole domain (or its last remaining version) does not mirror automatically: the confirm dialog offers Also delete this domain from GitHub, and the API takes delete_github=1. Failures are recorded on Last sync and on the domain Audit trail → GitHub tab; they never fail the registry write.

How files land. GitHubClient uses the GitHub Git Data API (blobs, trees, refs) over httpx. There is no git binary and no clone — a Databricks App cannot rely on either. One batch of path writes/deletes is one atomic commit, with a short retry if a concurrent push moved the branch.

Identity and secrets. global_config['github_config'] stores owner, repo, branch, optional base path, Databricks secret scope/key, author, and instance_uuid. The PAT itself is never persisted. GitHubSyncService.resolve_token reads the Databricks secret at push time, or ONTOBRICKS_GITHUB_TOKEN when no scope/key is set (local development).

Instance claim. Test connection writes .ontobricks/instance.json. A second instance cannot push to the same repository unless the operator ticks Take over.

Restore. GET /settings/github/obx rebuilds an OBX envelope from the JSON tree; Registry → Import → Load from GitHub repository feeds the same preview as a file import. Turtle is ignored on import.

Operator guide: User Guide — GitHub. Code: back.core.github.GitHubClient, back.objects.registry.gitsync, back.objects.domain.settings.GitHubSettings.

API Endpoints

Endpoint Method Description
/domain/list-versions GET List all versions of a domain
/domain/save-to-uc POST Save domain to Unity Catalog
/domain/load-from-uc POST Load a version from UC; on a domain switch closes the previously-open domain (releases its edit-lock) before loading, and returns a lock block
/domain/close POST Release the loaded version's edit-lock and reset the session
/domain/create-version POST Create new version (increment)
/domain/version-status GET Get current version status

Version Workflow

  1. First Save: Creates domains/{name}/V1/V1.json
  2. Update Save: Overwrites domains/{name}/V{ver}/V{ver}.json
  3. Create Version: Increments the version number, copying the previous version's parsed Knowledge Store documents (domain_documents rows) forward
  4. Load Version: Loads the requested version from V{ver}/V{ver}.json, regenerates R2RML and OWL

Auto-Save Flow (Design View)

User Action → OntoViz Event → Debounce → syncDesignToOntology → /ontology/save → Session Update

Triple Store & Graph DB Backends

OntoBricks separates two concerns:

  1. Triple Store (Lakehouse UC objects) — a family of Unity Catalog objects in the registry catalog.schema, always created by Knowledge Graph → Build. Not a single view: see Lakehouse Unity Catalog objects below.
  2. Graph DB — the queryable graph engine used by the Knowledge Graph, reasoning, and BFS / shortest-path helpers. Pluggable via the GraphDBFactory abstraction. When the per-domain backend is databricks, the Graph DB is those Delta tables; when it is lakebase or neo4j, Build also mirrors triples into that engine.

The active Graph DB engine is chosen per domain via graph_backend (none | lakebase | databricks | neo4j), set under Domain → Information → Knowledge Graph; connection settings live under Settings → Back end. none is the ontology-only mode: no graph is built and the MCP surface exposes ontology information only.

Layer Key Storage Query Language Source of truth
Delta Triple Store view / _data / _inferred / _graph Unity Catalog R2RML VIEW + Delta tables, or views only (SQL Warehouse) Spark SQL Yes (mapped triples = _data)
Lakebase Graph DB graph (engine lakebase) Postgres flat (subject, predicate, object) table on the App-bound Lakebase instance Postgres SQL Mirror of the mapped snapshot
Databricks Graph DB graph (engine databricks) Same Delta objects as the triple store (no second copy) Spark SQL The mapped snapshot itself
Neo4j Graph DB graph (engine neo4j) Bolt-connected Neo4j (Aura / self-hosted); flat-triple nodes per store Cypher Mirror of the mapped snapshot

Backend capability and object lifecycle

Build always creates the Unity Catalog triple-store family in the registry catalog.schema. The Graph DB then either is those objects (Lakehouse) or mirrors them (Lakebase, Neo4j). Copy below means a physical snapshot of rows; no copy means a VIEW that re-reads the source on each query.

Capability Lakehouse · table (copy) Lakehouse · views only (no mapped copy) Lakebase · app_managed Lakebase · managed_synced Neo4j
Chosen where Domain → Knowledge Graph, backend databricks, materialization table Same backend, materialization view Domain backend lakebase; Settings → Lakebase sync_mode Same backend, sync_mode=managed_synced Domain backend neo4j
Mapped triples _data TABLE — CTAS from the R2RML VIEW, then OPTIMIZE / Liquid Clustering _data VIEW — pass-through over the R2RML VIEW; no row copy UC _data is always a TABLE (analytics needs a Delta scan). Postgres _sync is a second copy loaded by the app (COPY FROM STDIN) UC _data TABLE. Postgres _sync is a second copy kept by Lakeflow UC _data TABLE. Neo4j nodes are a second copy (MERGE)
Inferred / app writes _inferred TABLE (truncated on full Build, then refilled) Same _inferred TABLE — inferred rows have no source table Postgres __app companion; UC _inferred still exists for the UC family Same __app companion; Lakeflow never writes it Stored as Neo4j triples in the same store label; no _adj_*
Interactive read façade _graph VIEW = _data UNION ALL _inferred Same _graph VIEW (each read re-runs mapping SQL through _data) Postgres union view g_<dom>_v<n> = _sync UNION ALL __app Same union view Bolt / Cypher against the store
Explorer hop + Preview indexes _adj_out, _adj_in, _entity_search, _props TABLES (always copies of a projection) Same four TABLES — views-only does not leave indexes as views Same four TABLES in the Postgres graph schema Same four Postgres tables None — native traversal / search
Who creates objects Build SQL Warehouse DDL Same warehouse (DDL only for _data; indexes still CTAS) Build warehouse for UC; FastAPI/psycopg for Postgres Build warehouse for UC schema; Lakeflow for _sync; app for __app, union view, indexes Build warehouse for UC; Bolt for Neo4j
Full Build Recreates gateway VIEW, replaces _data, truncates _inferred, refreshes _graph, rebuilds indexes Recreates gateway + _data VIEW, truncates _inferred, rebuilds indexes from live _graph Recreates UC family as tables, reloads _sync, truncates __app, rebuilds indexes Recreates UC family, triggers Lakeflow full refresh into _sync, truncates __app, rebuilds indexes Recreates UC family, MERGEs mapped triples into Neo4j
Refresh cache Rebuilds the four indexes from the existing _graph snapshot; does not recopy _data. Runs on the Build SQL Warehouse, never Lakehouse/RT Rebuilds indexes from live _graph (source changes are visible in the next index snapshot) Rebuilds indexes from the current Postgres union view Same Not available
When new source rows appear in Explorer hops Next full Build Next Refresh cache or Build (indexes stay a snapshot) Next Refresh cache or Build Next Refresh cache or Build (after Lakeflow has updated _sync) Immediately after Build MERGE
Analytics Scans _data TABLE Temporary …_analytics TABLE for the run, then drop Always scans UC _data TABLE, not Postgres Same Same UC _data TABLE

none (ontology-only) creates none of these objects.

Copy vs no-copy, more precisely:

  1. Mapped triples — only Lakehouse view avoids duplicating source-mapped rows. Lakehouse table, Lakebase, and Neo4j all freeze mapped triples (Lakebase and Neo4j freeze them twice: UC _data plus the engine store).
  2. Inferred triples — always stored (Delta _inferred or Lakebase __app). There is no live source to view over.
  3. Graph indexes — always stored tables when the backend supports them, even in Lakehouse views-only. Traversal and Preview never re-walk the mapping SQL per hop.

Cross-kind switch (_data TABLE ↔︎ VIEW) drops the stale relation first; Databricks cannot CREATE OR REPLACE a table over a view or the reverse.

Lakehouse Unity Catalog objects

Every successful Knowledge Graph → Build creates (or refreshes) four related objects that share the base name triplestore_<safe_domain>_V<version> in the domain's registry catalog.schema. Naming helpers live in src/back/core/graphdb/delta/_table_naming.py; the CTAS / companion SQL is in materialize.py.

Object Kind Role
triplestore_<domain>_V<n> VIEW Live R2RML mapping: SQL that projects source Unity Catalog tables into (subject, predicate, object). Refreshed on Build. Not a durable store — it recomputes from sources when queried.
…_data Delta TABLE or VIEW The mapped triples. By default a materialised snapshot of the VIEW (CREATE OR REPLACE TABLE … AS SELECT subject, predicate, object FROM <view>) clustered by (predicate, subject); under view-only materialization, a pass-through CREATE OR REPLACE VIEW over the same VIEW. Either way it is what Graph Analytics reads and the bulk half of the graph. Domains built before this step existed need one rebuild.
…_inferred Delta TABLE Writable companion with the same schema. Holds app-written / reasoning / cohort triples that are not in the mapped sources. Truncated on a full rebuild, then refilled as those features write. A table in both materialization modes — inferred triples have no source to be derived from.
…_graph VIEW Read façade: _data UNION ALL _inferred. Explorer, filters, stats, GraphQL, and most interactive reads use this when inferred triples are included.
source tables
    → R2RML VIEW          (live mapping definition)
    → _data               (TABLE: frozen mapped triples, or VIEW: pass-through)
         ↘
           _graph VIEW    (what the UI usually reads)
         ↗
      _inferred TABLE     (extra triples written by the app)

Why both a VIEW and _data? The R2RML view is the definition of “what the mapping says.” Analytics and heavy jobs need a fixed Delta table they can scan reliably (and identically across Lakehouse, Lakebase, and Neo4j backends). _data is that freeze. _graph then layers inferred rows on top for interactive reads without copying them into the mapped snapshot.

Materialization modes are a per-domain Lakehouse setting (info['lakehouse_materialization'], resolved by GraphDBFactory.resolve_lakehouse_materialization, applied by materialize.apply_data_relation):

  • view (new-domain default, Domain → Information → Backend → Access type) — no copy at all. _data is a view over the gateway, so every read re-executes the mapping SQL against the source tables and always sees live data. Builds only run DDL, and OPTIMIZE is skipped since there is nothing to compact.
  • table — CTAS + OPTIMIZE. One copy of the triples; reads are a single clustered Delta scan. A missing or unrecognised value still normalises to table so Lakehouse domains created before the option existed keep their copy.

Lakebase and Neo4j domains always get the table: the resolver returns table for any backend other than databricks, because their own graph is not what the analytics job reads.

Switching a domain between modes needs the stale relation of the other kind dropped first — Databricks refuses to replace a TABLE with a VIEW and vice versa — so apply_data_relation issues that cross-drop before creating either.

Analytics outputs (node metrics, _summary, _type_profiles, …) are a separate family written by the Lakeflow analytics job. They read _data; they are not part of the graph store. For a view-only domain the job cannot scan _data directly — its iterative BFS would re-derive the mapping on every pass — so JobMetrics.analytics_snapshot materialises a disposable …_analytics table for the run and drops it in a finally. A leftover from a run that died is grouped with its domain in Settings → Lakehouse for purging.

Adjacency index objects

In addition to the four-object triple-store family, Build produces graph-index tables for Explorer:

Object Kind Clustering Created when Used by
triplestore_<domain>_V<n>_adj_out Delta TABLE CLUSTER BY (src, predicate) End of Build (after _data in table mode; from _graph in view mode) Outgoing hops — Explorer expansion, expand_entity_neighbors
triplestore_<domain>_V<n>_adj_in Delta TABLE CLUSTER BY (dst, predicate) same Reverse (incoming) hops
triplestore_<domain>_V<n>_entity_search Delta TABLE CLUSTER BY (type_uri, label_lc) same Preview search (Inferred on)
triplestore_<domain>_V<n>_entity_search_asserted Delta TABLE same same, from _data Preview search (Inferred off)
triplestore_<domain>_V<n>_props Delta TABLE CLUSTER BY (subject) same Expansion payload — outgoing triples of typed subjects

Lakebase stores equivalent _adj_out, _adj_in, _entity_search, _entity_search_asserted, and _props tables. The entity table carries normalized URI/label fields and type metadata; _props has a btree index on subject. rebuild_adjacency reads hops/_props from the union view and asserted Preview from _sync. Neo4j uses native Bolt traversal/search and has no graph-index companions. GraphQL's typed list/nested-field resolvers and MCP's describe_entity / /triples/find find-and-traverse path read these same companions when ready — see GraphQL and MCP find read the same companions.

The Refresh cache action (builder/admin, Lakehouse and Lakebase only) reindexes _adj_out, _adj_in, _entity_search, and _props without rematerializing _data. Preview uses _entity_search when Inferred is enabled; asserted-only Preview keeps the SPO path. Expansion uses _props for its final payload join and retries against SPO when _props is missing. For Lakehouse, the refresh opens the Delta backend in write mode: GraphDBFactory resolves the configured Build SQL Warehouse and the fixed Thrift transport instead of the optional Lakehouse/RT query warehouse. This separation is required because Lakehouse/RT supports the Explorer read path but rejects the CREATE OR REPLACE TABLE DDL used by graph-index refreshes.

  • view materialization — adjacency CTAS runs from the live _graph VIEW (which itself re-executes the R2RML SQL against source tables, since _data is a pass-through view). Source changes are therefore captured at refresh time, but traversal still uses the adjacency snapshot and does not update automatically — a Refresh cache or full Build is required.
  • table materialization — adjacency is reindexed from the existing _data snapshot; new source rows do not appear until a full Build runs.
  • Lakebase — reindexes from the current reader-facing union view; because Lakebase graph data is always live in Postgres, the rebuild captures the current graph state without a stale _data snapshot to overcome. Traversal still uses the adjacency snapshot until the next Refresh cache or Build.

Lakehouse _adj_out, _adj_in, _entity_search, and _props are replaced sequentially, not via one cross-table atomic swap. If all indexes must be read from the same instant, avoid overlap with Build/Refresh and read after the task finishes.

On a table-mode Lakehouse domain, Explorer expansion (adjacency-driven) and a raw SPARQL scan of _graph can diverge between builds: expansion sees the adjacency snapshot while SPARQL sees _graph including _inferred. A full Build reconciles both.

Full detail: docs/graphdb-integration.md § Adjacency index objects.

Backend Abstraction

The Delta, Lakebase, and Neo4j paths each implement the single GraphDBBackend base (src/back/core/graphdb/GraphDBBackend.py) — DeltaFlatStore, LakebaseFlatStore, and Neo4jStore respectively. The base exposes the same surface for:

  • Table lifecycle: create_table, drop_table, table_exists
  • Triple operations: insert_triples, query_triples, count_triples
  • Named queries: get_aggregate_stats, find_subjects_by_type, bfs_traversal, …

The single GraphDBFactory returns the per-domain engine — Delta (databricks), Lakebase Postgres (lakebase), Neo4j (neo4j), or the raw read-only view store. Capability flags on GraphDBBackend (supports_cypher, is_cypher_backend, query_dialect) let SQL and Cypher engines coexist: SQL engines inherit the recursive-CTE named-query defaults, while Neo4jStore reports supports_cypher = True. Additional engines (Memgraph, Gremlin, …) can be added without rewiring the reasoning layer.

Lakebase Graph DB Architecture

Lakebase Postgres is one of three shipped Graph DB engines (alongside the Delta/databricks store and Neo4j). The implementation lives in src/back/core/graphdb/lakebase/ (LakebaseFlatStore, LakebaseBase, SyncedTableManager).

Storage model — per graph version, a three-object layout inside a configurable Postgres schema (default ontobricks_graph) on the App-bound Lakebase database: bulk _sync, writable __app, reader-facing union view g_<dom>_v<n>. Connection comes from the same OAuth/M2M credential the registry hybrid backend uses. See Backend capability and object lifecycle.

Two write modes (Lakebase only), configured under Settings → Back end → Lakebase:

  • managed_synced (what Settings → Lakebase proposes when sync_mode is unset) — Databricks Lakeflow keeps a Postgres synced table (g_<dom>_v<n>_sync) in lock-step with the R2RML view via a Snapshot pipeline (the view has no Change Data Feed, so Triggered / Continuous cannot run). The app only orchestrates (SyncedTableManager.ensure + trigger_and_wait); a writable companion table (g_<dom>_v<n>__app) absorbs reasoning / cohort writes; readers see both via a UNION view (g_<dom>_v<n>). See docs/graphdb-integration.md §9 for the full architecture.
  • app_managed (runtime fallback when the key is omitted, so existing workspaces that never saved Settings keep COPY ingest) — the FastAPI app streams warehouse rows in fetchmany batches and ingests them via COPY FROM STDIN into a per-batch temp table followed by INSERT … ON CONFLICT DO NOTHING.

Neo4j Graph DB Architecture

Neo4j is a Cypher-native engine for domains whose graph_backend is neo4j. The implementation lives in src/back/core/graphdb/neo4j/ and is split into a thin Neo4jStore façade over three services: Neo4jConnection (Bolt driver lifecycle + auth), Neo4jWriteOps (schema constraints and UNWIND/MERGE bulk writes), and Neo4jReadOps (statistics, entity lookup, KG-filter primitives, and reasoning helpers). Triples are stored as (:<store_label> {subject, predicate, object}) nodes, one label per logical store so Neo4j 5+ single-label CREATE CONSTRAINT applies.

Connection settings are configured under Settings → Back end → Neo4j. The Bolt password is resolved from the NEO4J_PASSWORD env var (a Databricks Apps secret resource) in the deployed app, falling back to the persisted engine_config only in local development; there is no raw-Cypher entry point (execute_query raises NotImplementedError) — all writes enter through insert_triples after ontology validation in the build pipeline. neo4j>=5 ships as a core dependency (pyproject.toml).

Adding a new engine — copy src/back/core/graphdb/_starter_kit/ExampleStore.py, implement the GraphDBBackend contract, register the engine key in GraphDBFactory, and add it to ALLOWED_GRAPH_ENGINES. Pure-SQL engines inherit the named-query defaults from GraphDBBackend; non-SQL engines (Cypher / Gremlin / SPARQL stores) override the relevant methods and may flip supports_cypher to re-enable the corresponding reasoning paths.


Reasoning Engine

OntoBricks includes a multi-phase reasoning engine (src/back/core/reasoning/) that brings formal ontology reasoning, rule evaluation, graph-structural inference, and constraint checking to the Databricks Lakehouse — without requiring an external reasoner or graph database.

Architecture

                    ReasoningService.run_full_reasoning()
                                  │
         ┌────────────────────────┼────────────────────────┐
         │                        │                        │
         ▼                        ▼                        ▼
   ┌───────────┐           ┌───────────┐           ┌───────────┐
   │  Phase 1  │           │  Phase 2  │           │  Phase 3  │
   │  T-Box    │           │   SWRL    │           │   Graph   │
   │ (OWL 2 RL)│           │  Rules    │           │ Reasoning │
   └─────┬─────┘           └─────┬─────┘           └─────┬─────┘
         │                       │                       │
   owlrl library           SWRLEngine              GraphDBBackend
   DeductiveClosure        └─ SQL translator       methods
   (OWLRL_Semantics)              │                ├─ transitive_closure
         │                        │                ├─ symmetric_expand
         ▼                        ▼                └─ shortest_path
   InferredTriple[]        RuleViolation[]               │
                           InferredTriple[]               ▼
                                                   InferredTriple[]
         │                       │                       │
         └───────────────────────┼───────────────────────┘
                                 ▼
                        ┌───────────────┐        ┌──────────────┐
                        │ Phase 4       │        │ Materialize  │
                        │ Constraints   │        │ (optional)   │
                        │ (skipped on   │        │ Write back   │
                        │  SQL engines) │        │ to graph DB  │
                        └───────────────┘        └──────────────┘

Phase 1: T-Box Reasoning — OWL 2 RL Profile

OWL 2 RL (Rule Language) is one of three profiles defined by the W3C OWL 2 specification. It is specifically designed for forward-chaining rule-based implementations — making it ideal for materialization workflows where inferred triples are written back to a triple store.

Implementation (src/back/core/reasoning/OWLRLReasoner.py):

The OWLRLReasoner class uses the owlrl Python library to perform deductive closure:

  1. Parses the domain's generated OWL Turtle into an RDFLib Graph
  2. Snapshots the original triple set
  3. Runs DeductiveClosure(OWLRL_Semantics).expand(graph) — applying all OWL 2 RL entailment rules via forward chaining
  4. Computes the delta (new triples minus original triples)
  5. Filters noise: blank-node triples, axiomatic vocabulary (RDF/RDFS/OWL/XSD namespaces), reflexive tautologies (X sameAs X, X subClassOf X), and redundant type declarations

What OWL 2 RL infers:

  • Subclass/subproperty entailments (rdfs:subClassOf, rdfs:subPropertyOf)
  • Domain and range typing (if P rdfs:domain C and x P y, then x rdf:type C)
  • Property characteristics (functional, inverse functional, transitive, symmetric)
  • Class axioms (equivalent classes, disjoint classes)
  • Property chain axioms
  • sameAs / differentFrom reasoning

Two modes:

  • T-Box only (default): Closure over the ontology schema — fast, suitable for all dataset sizes
  • T-Box + A-Box: Closure over ontology + instance data — suitable for small datasets (< ~50,000 triples)

Phase 2: SWRL Rule Evaluation

SWRL (Semantic Web Rule Language) extends OWL with Horn-clause rules. OntoBricks implements a custom SWRL engine that compiles rules into the query language of the active triple store backend.

Rule format:

Antecedent → Consequent

Where atoms are class assertions (Person(?x)) or property assertions (worksIn(?x, ?y)).

Implementation (src/back/core/reasoning/swrl/SWRLEngine.py, SWRLSQLTranslator.py):

Component File Role
SWRLEngine SWRLEngine.py Orchestrator — executes rules, collects results
SWRLSQLTranslator SWRLSQLTranslator.py Compiles SWRL atoms into SQL with multi-join + NOT EXISTS for violation detection

Execution modes:

  • Violation detection: Finds instances where the antecedent holds but the consequent does not (generates NOT EXISTS subqueries)
  • Materialization: Inserts inferred consequent triples into the store (generates INSERT statements)

Backend dispatch: The two SQL backends — DeltaFlatStore (Spark SQL on the SQL Warehouse) and LakebaseFlatStore (Postgres SQL) — use SWRLSQLTranslator. The Neo4jStore engine reports supports_cypher = True and returns a SWRLFlatCypherTranslator, but that translator is currently scaffolded — full SWRL → Cypher reasoning lands in a follow-up; on Neo4j the SWRL materialization phase therefore short-circuits. The capability flags (supports_cypher, query_dialect) on GraphDBBackend let the correct translator be selected per engine without touching SWRLEngine.

URI resolution: The engine builds a lowercase-name → URI map from the ontology, normalizing property URIs to the data namespace used by R2RML so that SWRL atom names match the predicates stored in the triple store.

Phase 3: Graph Reasoning

Graph reasoning leverages OWL property characteristics to perform structural inference on the triple store:

Transitive closure (owl:TransitiveProperty):

  • For properties like partOf, subRegionOf, or reportsTo
  • Discovers indirect relationships not explicitly asserted (if A partOf B and B partOf C, infers A partOf C)
  • Delta & Lakebase: SQL recursive CTE with depth limit

Symmetric expansion (owl:SymmetricProperty):

  • For properties like adjacentTo, siblingOf, or marriedTo
  • For every (a, P, b) where (b, P, a) is missing, adds the inverse edge
  • Delta & Lakebase: SQL NOT EXISTS anti-join

Shortest path:

  • SQL engines (Delta, Lakebase) use a BFS-bounded recursive CTE. The Cypher-capable Neo4j engine can back this with a native SHORTEST path once its Cypher query translation is completed (currently scaffolded).

Phase 4: Constraint Checking

Validates instance data in the triple store against formal ontology constraints:

Constraint Type OWL Construct Validation
Min cardinality owl:minCardinality Subject has at least N values for property
Max cardinality owl:maxCardinality Subject has at most N values for property
Exact cardinality owl:cardinality Subject has exactly N values for property
Functional owl:FunctionalProperty At most one distinct object per subject
Inverse functional owl:InverseFunctionalProperty At most one distinct subject per object
Value constraints OntoBricks extension notNull, startsWith, endsWith, contains, equals, matches (regex)
No orphans Global rule Every subject has an rdf:type assertion
Require labels Global rule Every typed entity has an rdfs:label

Execution:

  • On the Cypher-capable Neo4j engine: constraint checks will run as Cypher queries via ReasoningService once the Cypher translation layer is completed (currently scaffolded, so the constraint phase short-circuits with a skipped reason).
  • On Delta & Lakebase: Quality checks run as SQL queries via the Knowledge Graph quality pipeline

Reasoning Data Model

All reasoning phases produce standardized output via three dataclasses (src/back/core/reasoning/models.py):

Model Purpose
InferredTriple A new triple with subject, predicate, object, provenance (e.g., "owlrl", "swrl:RuleName", "graph:transitive")
RuleViolation A constraint failure with rule_name, subject, message, check_type
ReasoningResult Aggregated output: inferred_triples[], violations[], stats{} — mergeable across phases

Materialization

Inferred triples from any phase can be materialized (written back) to the triple store:

  • ReasoningService.materialize_inferred() inserts into the active Graph DB engine (Lakebase) and into the Delta view
  • ReasoningService.materialize_to_delta() provides a static method for Delta-specific materialization with table creation and data replacement

Key Files

File Purpose
src/back/core/reasoning/ReasoningService.py ReasoningService — orchestrates all phases
src/back/core/reasoning/OWLRLReasoner.py OWLRLReasoner — OWL 2 RL deductive closure
src/back/core/reasoning/swrl/SWRLEngine.py SWRLEngine — SWRL rule orchestration
src/back/core/reasoning/swrl/SWRLSQLTranslator.py SWRLSQLTranslator — SWRL → Spark / Postgres SQL compilation
src/back/core/reasoning/models.py InferredTriple, RuleViolation, ReasoningResult dataclasses
src/back/core/graphdb/GraphDBBackend.py Graph DB primitives: transitive_closure(), symmetric_expand(), shortest_path()

Graph Analysis — Community Detection

OntoBricks provides data cluster detection on the graph viewer, allowing users to discover communities of densely connected entities. Detection is available at two levels:

Client-Side (Graphology)

The frontend uses the graphology-communities-louvain algorithm (bundled with graphology-library) to run Louvain community detection directly in the browser on the currently displayed subgraph. This is instant and requires no backend call.

Server-Side (NetworkX)

For full-graph analysis, the backend CommunityDetector service (src/back/core/graph_analysis/CommunityDetector.py) loads all triples from the triple store, builds an undirected NetworkX graph (filtering out RDF type/label predicates), and runs one of three algorithms:

Algorithm NetworkX Function Description
Louvain community.louvain_communities() Modularity-maximizing hierarchical clustering (default)
Label Propagation community.label_propagation_communities() Fast, near-linear-time detection
Greedy Modularity community.greedy_modularity_communities() Greedy agglomerative approach

The result includes cluster membership, modularity score, and per-cluster member lists. It is returned to the frontend via POST /dtwin/clusters/detect.

Visualization

Detected clusters can be visualized in several ways:

  • Color by cluster — nodes are recolored by community assignment instead of entity type
  • Resolution slider — controls Louvain granularity (higher resolution = more clusters)
  • Collapse/expand — clusters can be collapsed into super-nodes showing size and member count; clicking a super-node shows its members in the detail panel

File Reference

File Purpose
src/back/core/graph_analysis/CommunityDetector.py CommunityDetector — loads triples, builds NetworkX graph, runs algorithm
src/back/core/graph_analysis/models.py ClusterRequest, ClusterResult, DetectionResult, DetectionStats dataclasses
src/api/routers/internal/dtwin.py POST /dtwin/clusters/detect endpoint
src/back/objects/digitaltwin/digitaltwin.py DigitalTwin.detect_clusters() method
src/front/static/query/js/query-sigmagraph.js Client-side Louvain detection, cluster UI logic, super-node rendering
src/front/templates/partials/dtwin/_query_sigmagraph.html Data Clusters sidebar panel
src/front/static/query/css/query-sigmagraph.css Cluster panel and chip styles

SHACL Data Quality

OntoBricks includes a SHACL (Shapes Constraint Language) module (src/back/core/w3c/shacl/) that provides W3C-standard data quality validation for the graph viewer.

Architecture

                    SHACLService
                        │
         ┌──────────────┼──────────────┐
         ▼              ▼              ▼
   ┌───────────┐  ┌───────────┐  ┌───────────┐
   │  Shapes   │  │  Turtle   │  │ Validate  │
   │   CRUD    │  │ Round-Trip│  │ & Execute │
   └───────────┘  └───────────┘  └───────────┘
   create/update  SHACLGenerator  PySHACL (in-memory)
   delete/list    SHACLParser     shape_to_sql (SQL)

Quality Categories

Shapes are organized into six data quality categories:

Category SHACL Constraints Example
Completeness sh:minCount Every entity must have a label
Cardinality sh:minCount, sh:maxCount At most 3 phone numbers per person
Uniqueness sh:hasValue, sh:in Entity IDs must be unique
Consistency sh:class, sh:node Relationship targets must be of the correct type
Conformance sh:pattern, sh:datatype Email must match regex, dates must be xsd:date
Structural sh:closed, sh:sparql No unexpected properties, custom SPARQL checks

Key Components

File Class Purpose
src/back/core/w3c/shacl/SHACLService.py SHACLService Shape CRUD, legacy constraint migration, SQL compilation, PySHACL validation
src/back/core/w3c/shacl/SHACLGenerator.py SHACLGenerator Builds RDFLib graph of sh:NodeShape / sh:PropertyShape and serializes to Turtle
src/back/core/w3c/shacl/SHACLParser.py SHACLParser Parses Turtle (or other RDF formats) into internal shape dictionaries

Execution Modes

  • PySHACL validation (validate_graph): Validates an RDF graph against shapes in-memory using the pyshacl library — returns conformance status, violation list, and report text
  • SQL compilation (shape_to_sql): Compiles individual shapes into Spark SQL queries against the flat (subject, predicate, object) triple table — supports sh:minCount, sh:maxCount, sh:pattern, sh:hasValue, sh:class
  • In-memory evaluation (evaluate_shape_in_memory): Lightweight evaluation for simple shapes without SQL execution
  • Legacy migration (migrate_legacy_constraints): Converts existing OntoBricks constraint definitions to SHACL shape dictionaries

UI Integration

  • Ontology → Data Quality sidebar section: Define, edit, and manage SHACL shapes visually with category-based organization
  • Knowledge Graph → Data Quality sidebar section: Run shapes against the triple store with violation reporting

Technology Stack

Backend

Technology Version Purpose
Python 3.10+ Core language
FastAPI 0.109+ Web framework
Uvicorn latest ASGI server
RDFLib 7.0+ RDF/OWL operations
owlrl 7.0+ OWL 2 RL forward-chaining reasoner (deductive closure on RDFLib graphs)
PySHACL 0.26+ W3C SHACL validator for RDFLib graphs (data quality shapes validation)
psycopg 3.2+ Postgres driver for the Lakebase Graph DB engine
Databricks SQL Connector 3.0+ Database connectivity
MLflow 2.19+ Agent tracing, evaluation, and Databricks Agent Framework
FastMCP 2.3+ MCP server SDK for LLM tool integration
Strawberry GraphQL 0.220+ Auto-generated typed GraphQL schema from ontology

Frontend

Technology Version Purpose
Bootstrap 5.3 UI framework
Bootstrap Icons 1.11 Icon library
Sigma.js 3.0.2 Graph Viewer visualization (WebGL)
Graphology 0.26.0 Graph data model and algorithms
D3.js 7.x Data-driven DOM manipulation
Grid.js latest Advanced data tables
OntoViz 1.0 Visual entity-relationship designer
Vanilla JavaScript ES6+ Client-side logic

External Standards

Standard Version Purpose
RDF 1.1 Data model
OWL 2 Ontology language
R2RML W3C Rec Mapping language
SPARQL 1.1 Query language
SWRL W3C Sub Rule language
SHACL W3C Rec Data quality validation
Turtle 1.1 RDF serialization

Logging

OntoBricks uses Python's standard logging module with logging.config.dictConfig for a structured, log4J-style configuration. All configuration lives under src/back/core/logging/ (LogManager.py implements setup and logger naming).

Architecture

Component Description
src/back/core/logging/ Package — LogManager builds and applies a dictConfig; setup_logging / get_logger are re-exported from __init__.py
setup_logging() Called once at startup (in run.py) before the app is created
get_logger(name) Helper to obtain a child logger under the ontobricks namespace

Loggers

Logger Purpose
ontobricks Application logger — back.*, front.*, shared.*, and api.* modules use child loggers
uvicorn / uvicorn.access / uvicorn.error HTTP server logs
fastapi Framework logs
Root Catch-all at WARNING level

Handlers

Handler Type Target
console StreamHandler stdout — visible in Databricks App logs
file RotatingFileHandler Rotating log file (10 MB, 5 backups)

The file handler writes to a path determined by (in priority order):

  1. LOG_DIR environment variable
  2. /local_disk0/logs when running inside Databricks Apps
  3. ./logs for local development

Format

All log lines follow a detailed ISO-8601 format:

2026-02-17T14:30:05+0000 | INFO     | ontobricks.shared.fastapi.main | main.lifespan:95 | OntoBricks FastAPI starting

Configuration

Logging is controlled via environment variables or Pydantic Settings:

Variable Default Description
LOG_LEVEL INFO DEBUG, INFO, WARNING, ERROR, CRITICAL
LOG_DIR (auto) Directory for the rotating log file
LOG_FILE ontobricks.log Filename inside LOG_DIR
LOG_FORMAT (text) Set to json to emit structured JSON lines (one JSON object per log entry with ts, level, logger, module, func, line, msg fields)

Structured JSON Logging

Set LOG_FORMAT=json to switch both console and file handlers to JSON-line output. Each entry is a single JSON object:

{"ts": "2026-04-19T10:30:05+00:00", "level": "INFO", "logger": "ontobricks.shared.fastapi.main", "module": "main", "func": "lifespan", "line": 95, "msg": "OntoBricks FastAPI starting"}

This mode is recommended for production deployments where logs are aggregated by external tools (e.g. Databricks log console, ELK, Datadog).

Request Timing

The RequestTimingMiddleware (shared/fastapi/timing.py) logs method, path, status_code, and duration_ms for every non-static request. Combined with JSON logging, this provides per-endpoint latency visibility without external APM tooling.

Usage in Modules

from back.core.logging import get_logger

logger = get_logger(__name__)
logger.info("Processing %d triples", count)

MLflow Observability

OntoBricks integrates MLflow for agent observability, evaluation, and compatibility with the Databricks Agent Framework.

Tracing Architecture

┌─────────────────────────────────────────────────┐
│                 FastAPI Startup                   │
│   setup_tracing() → mlflow.set_experiment(...)   │
│                  mlflow.tracing.enable()          │
└──────────────────────┬──────────────────────────┘
                       │
      ┌────────────────┼────────────────┐
      ▼                ▼                ▼
 @trace_agent     @trace_llm      @trace_tool
 (run_agent)      (call_serving_endpoint) (_execute_tool)
      │                │                │
      └────────────────┼────────────────┘
                       ▼
              MLflow Tracking Server
         (local mlflow.db or Databricks)

Every agent invocation produces a nested span tree:

Span Type Decorator Captures
AGENT @trace_agent Full run — inputs (secrets excluded), result status, iterations, token usage
LLM @trace_llm Each LLM call — endpoint, message count, finish reason, prompt/completion tokens
TOOL @trace_tool Each tool dispatch — tool name, arguments, result length

Tracking Destination

Environment Tracking URI Experiment Path Storage
Local dev (default) (not set) ontobricks-agents mlflow.db + mlruns/ on disk
Local dev (persistent) MLFLOW_TRACKING_URI=databricks /Shared/ontobricks-agents Databricks workspace
Databricks App MLFLOW_TRACKING_URI=databricks (set in app.yaml) /Shared/ontobricks-agents Databricks workspace

When the tracking URI is databricks, experiment names are automatically resolved to absolute workspace paths (/Shared/<name>) so that traces are accessible from the workspace Experiments UI.

Viewing Traces

In the Databricks workspace:

  1. Navigate to Machine Learning > Experiments
  2. Open the /Shared/ontobricks-agents experiment
  3. Click any run, then the Traces tab to see the full span tree

Databricks Agent Framework

The Ontology Assistant agent has a ResponsesAgent wrapper (src/agents/agent_ontology_assistant/responses_agent.py) that implements the MLflow ResponsesAgent interface. This enables:

  • AI Playground — interactive testing
  • Agent Evaluation — quality measurement with LLM judges
  • Model Serving — deployment as a managed endpoint
  • MLflow Model Logging — versioning and tracking via log_model.py

Configuration

Variable Default Description
MLFLOW_TRACKING_URI (none) Set to databricks for persistent traces
ONTOBRICKS_MLFLOW_EXPERIMENT ontobricks-agents Experiment name (auto-prefixed with /Shared/ on Databricks)

Tracing degrades gracefully: if MLflow is not configured or the tracking server is unreachable, agents run normally without traces.

Key Files

File Purpose
src/agents/tracing.py Setup, decorators (trace_agent, trace_llm, trace_tool), secret filtering
src/agents/agent_ontology_assistant/responses_agent.py ResponsesAgent wrapper for the Databricks Agent Framework
src/agents/agent_ontology_assistant/log_model.py Script to log the agent model to MLflow
src/shared/fastapi/main.py Calls setup_tracing() at application startup

Performance Infrastructure

SQL Connection Pooling

SQLWarehouse maintains a queue.Queue-based pool of reusable database connections (src/back/core/databricks/SQLWarehouse.py). Instead of opening a fresh databricks.sql.connect() per query (costly due to TLS handshakes), connections are borrowed from the pool and returned after use. Stale connections (idle > 300 s) are discarded automatically.

Lakehouse/RT graph reads select StatementExecutionWarehouse inside Databricks Apps. It uses direct SEA INLINE responses and workspace-host internal chunk links, so this route does not create pooled connector sessions or require CloudFetch egress. Local RT reads keep SQLWarehouse with Kernel.

Parameter Default Notes
Pool size 8 Max concurrent connections per warehouse
Max idle 300 s Connections older than this are replaced

Dedicated Thread Pool

All blocking Databricks I/O runs through run_blocking() in DatabricksHelpers.py, which dispatches to a dedicated ThreadPoolExecutor instead of the default asyncio pool. This prevents SQL latency from starving the event loop.

Variable Default Description
ONTOBRICKS_THREAD_POOL_SIZE 20 Max workers for blocking I/O

Security Considerations

Authentication

  • Personal Access Token (development)
  • Service Principal (production/Databricks Apps)
  • Tokens stored in environment variables

CSRF Protection

  • Double-submit cookie pattern via CSRFMiddleware (shared/fastapi/csrf.py)
  • A csrf_token cookie is set on first visit; state-changing requests (POST, PUT, PATCH, DELETE) must include the same value in an X-CSRF-Token header. A missing cookie, a missing header or a mismatch is rejected with 403 (constant-time comparison); non-browser clients must use /api/ or /graphql/
  • navigator.sendBeacon cannot set the header — unload-time saves use fetch(..., {keepalive: true}) instead
  • The browser-side fetch() wrapper in utils.js attaches the header automatically
  • Bypass paths: /static/, /health, /api/, /graphql/, docs endpoints
  • Disabled via CSRF_DISABLED=1 for automated test suites

Data Protection

  • Session cookies use secure=True and samesite=lax when running as a Databricks App (DATABRICKS_APP_PORT set), ensuring cookies are only sent over HTTPS
  • No credentials persisted to disk
  • GitHub PATs are resolved live from a Databricks secret (or ONTOBRICKS_GITHUB_TOKEN locally); only the secret scope/key is stored in github_config
  • HTTPS enforced in production

SQL Injection Prevention

  • Parameterized queries via Databricks SQL Connector
  • Read-only query validation for test queries

External REST API

OntoBricks provides a stateless REST API at /api/v1/ for external applications to:

Version lifecycle & API access. Each domain version has a lifecycle status — DRAFT → IN-REVIEW → PUBLISHED (transitions enforced server-side in back.objects.registry.version_lifecycle). The external REST API, GraphQL (/api/v1/graphql) and MCP only serve PUBLISHED versions and default to the numeric-latest PUBLISHED version.

The PermissionMiddleware lifecycle gate distinguishes between design edits and data-refresh ops:

  • Design edits (ontology/mapping changes, metadata saves, document uploads, design-view CRUD) are blocked on non-DRAFT versions for all roles — the design is frozen.
  • Data-refresh ops (/dtwin/sync/start, /dtwin/sync/load, /dtwin/reasoning/materialize) are not status-gated. They re-materialise graph triples from source data using the frozen design and can be triggered on PUBLISHED / IN-REVIEW versions without reverting to DRAFT. They remain guarded by the builder role.
  • Read-only operations (Explorer filter, stats, status, SPARQL, GraphQL) remain accessible on all statuses.

On top of the lifecycle gate, a single-editor lock (EditLockService + the Lakebase domain_edit_locks table) enforces that only one user edits a given DRAFT (domain, version) at a time. The model is renew-only lease: the first opener acquires the lock (on POST /domain/load-from-uc), later openers are read-only, and the lock is held until the holder explicitly closes the domain (POST /domain/close releases the lock then resets the session), an admin takes over (POST /domain/edit-lock/acquire with force), the version leaves DRAFT (force_release), or — when a lease TTL is configured (Settings → Global → Edit Lock Lease, or the ONTOBRICKS_EDIT_LOCK_TTL_S env var; the Settings value wins, seconds, default 600, 0 disables) — its lease lapses. The lease clock is the heartbeat_at column: acquire_edit_lock's ON CONFLICT reclaims a lock only when the current holder has not renewed within the TTL, and the holder keeps it alive via POST /domain/edit-lock/renew (a client timer pinging every ~TTL/3) plus the per-page non-forcing acquire. The lock is never released on unload, so ordinary multi-page navigation cannot free it mid-session — only the absence of a renew for a full TTL can. PermissionMiddleware is authoritative — it 403s a non-holder's mutating request on a DRAFT version (admins are not exempt) but treats a stale lease as free (blocking_holder ignores it).

Opening a different domain closes the previous one first. On a domain switch, load-from-uc releases the prior domain's lock (EditLockService.release_prev) before loading the new one, so a user never holds two DRAFT locks at once. A same-domain version switch instead releases the old version's lock after the new one loads (on_domain_loaded), avoiding a needless release/re-acquire when reopening the same version.

Admins get a registry-wide view of every active lock via Settings › Locks (GET /settings/locks → EditLockService.list_all → store.list_all_edit_locks) and can force-unlock any (folder, version) without opening that domain (POST /settings/locks/release → EditLockService.admin_release); both endpoints are admin-only. When the lock backend is unavailable (e.g. the table is missing) EditLockService._shape degrades to permissive rather than presenting a phantom "another user" lock. domain_edit_locks is provisioned as the schema owner by the deploy migration (scripts/bootstrap/lakebase-perms.sh), because the app service principal cannot self-heal the table's FK to domains.

The lifecycle replaces the old per-version "Active"/mcp_enabled toggle.

Ontology-only publish. The DRAFT -> IN-REVIEW precondition accepts either a Knowledge Graph build (last_build) or a valid ontology, so a domain with only an ontology (no mapping, no graph) goes through the normal workflow. GET /api/v1/domains then reports graph_backend:"none" and has_graph:false, and the MCP server exposes describe_ontology alone for that domain (see MCP per-domain policy).

Available Endpoints

Domain API (/api/v1/domains, /api/v1/domain/...):

Endpoint Method Description
/api/v1/domains GET List registry domains with ≥1 PUBLISHED version, configured backend, and graph availability
/api/v1/domain/versions GET List versions for a named domain
/api/v1/domain/design-status GET Design status (ontology, metadata, mapping readiness)
/api/v1/domain/ontology GET Get domain OWL ontology (Turtle)
/api/v1/domain/r2rml GET Get R2RML mapping (Turtle)
/api/v1/domain/sparksql GET Get generated Spark SQL

Knowledge Graph API (/api/v1/digitaltwin/):

Endpoint Method Description
/api/v1/digitaltwin/registry GET Get registry configuration
/api/v1/digitaltwin/status GET Triple store status
/api/v1/digitaltwin/stats GET Triple store statistics
/api/v1/digitaltwin/build POST Trigger triple store build
/api/v1/digitaltwin/triples/find GET BFS entity search/traversal

Legacy v1 API:

Endpoint Method Description
/api/v1/health GET Health check
/api/v1/domains/list POST List domains in Unity Catalog
/api/v1/domain/info POST Get domain metadata
/api/v1/domain/ontology POST Get ontology details
/api/v1/domain/ontology/classes POST Get ontology classes
/api/v1/domain/ontology/properties POST Get ontology properties
/api/v1/domain/mappings POST Get mapping details
/api/v1/domain/r2rml POST Get R2RML content
/api/v1/query POST Execute SPARQL query
/api/v1/query/validate POST Validate SPARQL syntax
/api/v1/query/samples POST Get sample queries

GraphQL API:

Endpoint Method Description
/graphql GET List API-enabled domains with a materialized graph
/graphql/settings/depth GET GraphQL depth settings
/graphql/{project_name} GET GraphiQL playground
/graphql/{project_name} POST Execute GraphQL query
/graphql/{project_name}/schema GET SDL schema

Authentication

API endpoints accept Databricks credentials via:

  • Headers: X-Databricks-Host, X-Databricks-Token
  • Request Body: databricks_host, databricks_token

Example Usage

import requests

response = requests.post(
    "http://localhost:8000/api/v1/query",
    headers={
        "Content-Type": "application/json",
        "X-Databricks-Host": "https://workspace.databricks.com",
        "X-Databricks-Token": "dapi..."
    },
    json={
        "project_path": "/Volumes/catalog/schema/volume/project.json",
        "query": "SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 10"
    }
)
results = response.json()

See API Documentation for complete endpoint reference.


Extension Points

  1. Additional Data Sources: Implement new client classes in src/back/core/databricks/
  2. Custom R2RML Patterns: Extend R2RMLGenerator in src/back/core/w3c/r2rml/R2RMLGenerator.py
  3. New Output Formats: Add serializers in mapping or ontology modules
  4. Additional SPARQL Features: Extend SparqlTranslator in src/back/core/w3c/sparql/SparqlTranslator.py
  5. Custom Visualizations: Extend Sigma.js graph viewer in query template
  6. Authentication Providers: Add new auth methods in DatabricksClient
  7. OntoViz Extensions: Add new entity/relationship types, custom rendering
  8. Graph DB Engines: Implement GraphDBBackend in src/back/core/graphdb/ (Lakebase Postgres, Unity Catalog Delta, and Neo4j ship today; the _starter_kit/ExampleStore.py template plus GraphDBFactory make it straightforward to add Memgraph, Gremlin, or other engines).
  9. Theming: Modify OntoViz CSS variables for custom themes
  10. SWRL Built-ins: Extend the SWRL engine (src/back/core/reasoning/swrl/SWRLEngine.py) with additional built-in atoms beyond class and property assertions (e.g., math, string, comparison built-ins)
  11. Reasoning Profiles: Add new reasoning profiles beyond OWL 2 RL (e.g., OWL 2 EL) by implementing alternative reasoner classes in src/back/core/reasoning/
  12. Custom Constraint Types: Add domain-specific constraint validators to the constraint checking phase in ReasoningService
  13. New LLM Agents: Add agents under src/agents/ using the shared tool framework (see Agentic Architecture)
  14. New Agent Tools: Add reusable tools in src/agents/tools/ for agents to compose
  15. GraphQL Customization: Extend the auto-generated schema in src/back/core/graphql/ — add custom resolvers, DataLoader batching, or subscription support
  16. MCP Server Tools: Add new MCP tools in src/mcp-server/server/app.py for additional knowledge-graph operations
  17. Industry Ontology Importers: Extend FIBO, CDISC, IOF services in src/back/core/industry/ for domain-specific ontology support

References

W3C Standards

Libraries & Tools


Component guides (merged)

The following sections were previously separate documents.

Agentic Architecture

Overview

OntoBricks uses LLM-powered agents to automate complex, multi-step tasks that would otherwise require significant manual effort. Each agent follows an MCP-style (Model Context Protocol) pattern: an autonomous loop where the LLM reasons about the task, calls tools to gather context or perform actions, and iterates until the goal is achieved.

All in-app agents use the LLM saved on the domain (Domain Information → AI): an executable Unity Catalog AI Gateway model service (kind: "ai_gateway", POST /ai-gateway/mlflow/v1/chat/completions with model set to the three-part name) or a legacy Model Serving endpoint (kind: "serving", POST /serving-endpoints/{name}/invocations). They do not pick a model independently. An empty target (No LLM) is rejected before any LLM request. Agents degrade gracefully if the selected endpoint does not support function calling.

In addition to the UI-driven agents, OntoBricks provides an MCP server (mcp-ontobricks) that exposes knowledge-graph tools to LLM clients (Databricks Playground, Cursor, Claude Desktop) via the Model Context Protocol. The MCP server is a separate Databricks App that calls the main app's REST and GraphQL APIs. See MCP Server for details.

┌─────────────────────────────────────────────────────────┐
│                    FastAPI Route                         │
│  (creates task, spawns background thread)                │
├─────────────────────────────────────────────────────────┤
│                                                         │
│   ┌───────────────────────────────────────────────┐     │
│   │              Agent Engine                      │     │
│   │                                                │     │
│   │   System Prompt                                │     │
│   │       ↓                                        │     │
│   │   ┌──────────┐    tool_calls    ┌──────────┐  │     │
│   │   │   LLM    │ ───────────────→ │  Tools   │  │     │
│   │   │ (iterate)│ ←─────────────── │ (execute)│  │     │
│   │   └──────────┘   tool_results   └──────────┘  │     │
│   │       ↓                                        │     │
│   │   AgentResult                                  │     │
│   └───────────────────────────────────────────────┘     │
│                                                         │
│   TaskManager.complete_task(result)                      │
│   Frontend polls /tasks/{id} → applies result            │
└─────────────────────────────────────────────────────────┘

Agents

1. OWL Generator Agent (agent_owl_generator)

Purpose: Autonomously generate a complete OWL ontology (Turtle format) from domain metadata and the parsed documents in the Lakebase Knowledge Store (domain_documents).

Parameter Value
Max iterations 10
LLM timeout 180s
Max tokens 4096
Temperature 0.1

Workflow:

  1. Receives a user prompt describing the desired ontology
  2. Calls get_metadata and get_table_detail to understand the data schema
  3. Calls list_documents and read_document to ingest parsed reference material from the Lakebase Knowledge Store
  4. Generates OWL/Turtle output based on gathered context

Tools used: get_metadata, get_table_detail, list_documents, read_document

Invoked by: POST /ontology/generate → background thread → TaskManager


2. Auto-Mapping Agent (agent_auto_assignment)

Purpose: Autonomously map ontology entities and relationships to SQL queries against the domain's Databricks tables. The agent writes SQL, validates it by executing queries, and submits the finalized mappings.

Parameter Value
Max iterations 60 (batch) / 15 (single-item)
LLM timeout 180s
Max tokens 2048
Temperature 0.1
Iteration delay 3s between LLM calls
Chunk size 5 items per agent run (AUTO_ASSIGN_CHUNK_SIZE)
Chunk cooldown 15s between chunks (AUTO_ASSIGN_CHUNK_COOLDOWN)

Workflow:

  1. Calls get_ontology to see entities, relationships, and their attributes
  2. Calls get_metadata to understand available tables and columns
  3. For each entity/relationship:
    • Writes a SQL query using execute_sql to validate it
    • Iterates on SQL errors until the query succeeds
    • Calls submit_entity_mapping or submit_relationship_mapping to finalize
  4. Repeats until all items are mapped or iteration limit is reached

Tools used: get_ontology, get_metadata, execute_sql, submit_entity_mapping, submit_relationship_mapping

Invoked by:

  • Batch: POST /mapping/auto-assign/start → background thread → TaskManager. Large jobs are split into chunks of AUTO_ASSIGN_CHUNK_SIZE items; each chunk runs its own agent loop with a AUTO_ASSIGN_CHUNK_COOLDOWN pause between chunks to avoid LLM rate limits (429 errors). Partial results accumulate across chunks.
  • Single-item: POST /mapping/auto-assign/single → background thread → TaskManager (processes one entity or relationship)

Single-item mode: The same agent engine is used with max_iterations=15. The ontology payload is scoped to the single target item. The frontend fires the request, polls /tasks/{id}, and saves the result directly to MappingState.config by URI — enabling concurrent auto-maps on different items.


3. Auto Icon Assign Agent (agent_auto_icon_assign)

Purpose: Choose visually representative emoji icons for each ontology entity by analyzing entity names, attributes, and data context.

Parameter Value
Max iterations 8
LLM timeout 120s
Max tokens 2048
Temperature 0.3

Workflow:

  1. Calls get_ontology to see all entities and their properties
  2. Optionally calls get_metadata to understand what each entity represents
  3. Selects an emoji for each entity and calls assign_icons with the full mapping

Tools used: get_ontology, get_metadata, assign_icons

Invoked by: Ontology Studio toolbar (#mapAutoAssignIcons) → POST /ontology/auto-assign-icons (background task). The frontend sends entities that still use the default icon. When every entity already has a custom icon, it asks the user to confirm a full remap, then sends every entity name.


4. Ontology Assistant (agent_ontology_assistant)

Purpose: Interactive conversational agent that can modify the domain ontology based on natural language instructions — add/remove entities, adjust relationships, clean orphans, and answer questions about the ontology.

Parameter Value
Max iterations 15
LLM timeout 180s
Max tokens 4096
Temperature 0.1

Workflow:

  1. Receives a user message (e.g., "Add an entity called Vehicle with attributes: plate, color")
  2. Calls get_ontology to understand the current ontology state
  3. Modifies the ontology (adds/removes entities, relationships, properties)
  4. Returns the updated ontology for the frontend to apply

Tools used: get_ontology, plus ontology mutation functions built into the engine

Invoked by: POST /ontology/assistant/chat (Designer UI) and POST /ontology/assistant/invoke (ResponsesAgent). Both routes inject the saved domain endpoint_name and endpoint_kind via require_domain_llm before the agent runs.

Databricks Agent Framework: This agent has a ResponsesAgent wrapper (responses_agent.py) that implements the MLflow ResponsesAgent interface, enabling AI Playground testing, Agent Evaluation, Model Serving deployment, and MLflow model logging (see the MLflow section in Architecture).


Shared Tools

All tools live in src/agents/tools/ and follow a consistent pattern:

  • Definition: An OpenAI function-calling JSON schema (TOOL_DEFINITIONS list)
  • Handler: A Python function that receives ToolContext as its first argument (TOOL_HANDLERS dict)
  • Composability: Each agent's tools.py assembles only the tools it needs

Tool Catalog

Tool Module Description Used By
get_metadata metadata.py Returns domain table schemas (names, columns, types) All agents
get_table_detail metadata.py Returns detailed schema for a specific table OWL Generator
list_documents documents.py Lists Knowledge Store documents from the Lakebase domain_documents table OWL Generator
read_document documents.py Reads the parsed text of a specific Knowledge Store document from Lakebase OWL Generator
get_ontology ontology.py Returns current ontology (entities, relationships, attributes) Auto-Mapping, Icon Mapping, Ontology Assistant
execute_sql sql.py Executes a SQL query via Databricks SQL Warehouse Auto-Mapping
submit_entity_mapping mapping.py Saves a validated entity → SQL mapping Auto-Mapping
submit_relationship_mapping mapping.py Saves a validated relationship → SQL mapping Auto-Mapping
assign_icons icons.py Saves entity → emoji icon mapping Icon Mapping

ToolContext

The ToolContext dataclass (tools/context.py) provides shared runtime state to all tools:

@dataclass
class ToolContext:
    # Common (all agents)
    host: str                # Databricks workspace URL
    token: str               # Databricks access token
    metadata: dict           # Domain table metadata

    # OWL Generator
    uc_location: dict        # Unity Catalog file location

    # Auto-Mapping
    client: Any              # DatabricksClient for SQL execution
    ontology: dict           # Current ontology data
    entity_mappings: list    # Accumulated entity mapping results
    relationship_mappings: list  # Accumulated relationship mapping results

    # Icon Assign
    icon_results: dict       # Accumulated icon assignments

Each agent populates only the fields it needs; unused fields remain at their defaults.


Agent Engine Pattern

All three agents share the same engine structure (defined independently in each engine.py):

Core Loop

1. Build messages = [system_prompt, user_prompt]
2. For iteration in 1..MAX_ITERATIONS:
   a. Call LLM with messages + tool_definitions
   b. If response contains tool_calls:
      - Execute each tool via TOOL_HANDLERS
      - Append tool results to messages
      - Continue loop
   c. If response is plain text (no tool_calls):
      - Extract final output
      - Break
3. Build AgentResult from accumulated state

Key Functions

Function Description
run_agent(...) Public entry point — sets up context, runs the loop, returns AgentResult
call_serving_endpoint(...) Shared transport in agents.engine_base; build_llm_request routes AI Gateway vs Model Serving from the saved endpoint_kind
_execute_tool(...) Dispatches a tool call to the appropriate handler
_extract_content(...) Extracts text from LLM response (handles different response formats)

Fallback Mode

If the LLM endpoint returns HTTP 400/422 (indicating it doesn't support the tools parameter), the OWL Generator and Icon Assign agents automatically retry without tools, falling back to single-shot generation. The Auto-Mapping agent does not fall back because its workflow fundamentally requires tool calls (SQL execution, mapping submission).

Task Integration

Agents are invoked from FastAPI routes via background threads:

## Route handler
tm = get_task_manager()
task = tm.create_task(name="...", task_type="...", steps=[...])

def _run():
    tm.start_task(task.id)
    result = run_agent(...)
    tm.complete_task(task.id, result=result)

thread = threading.Thread(target=_run, daemon=True)
thread.start()
return {"success": True, "task_id": task.id}

The frontend polls GET /tasks/{task_id} until the task completes, then applies the result.


Adding a New Agent

  1. Create the agent directory: src/agents/agent_<name>/
  2. Define tools in src/agents/tools/ (reuse existing tools where possible)
  3. Create tools.py: Assemble TOOL_DEFINITIONS and TOOL_HANDLERS from shared tools
  4. Create engine.py: Implement run_agent() with a system prompt and the agentic loop
  5. Create __init__.py: Export run_agent and AgentResult
  6. Wire the route: Create a FastAPI endpoint that spawns the agent in a background thread via TaskManager
  7. Wire the frontend: Call the endpoint, poll /tasks/{id}, and apply the result

Tool Authoring Convention

Each tool module exports:

## Handler function
def tool_<name>(ctx: ToolContext, **kwargs) -> str:
    """Must return a JSON string."""
    ...

## OpenAI function-calling definition
<NAME>_TOOL_DEFINITIONS: List[dict] = [{ "type": "function", "function": {...} }]

## Name → handler mapping
<NAME>_TOOL_HANDLERS: Dict[str, Callable] = { "<name>": tool_<name> }

Architecture Decisions

Decision Rationale
Agents run in background threads Keeps the FastAPI event loop responsive; users can continue working
Fire-and-forget with polling Enables concurrent auto-maps on different entities
URI-keyed saves Results are saved by target URI, not by current panel state — avoids race conditions when the user navigates during processing
Shared ToolContext Avoids passing many arguments; each agent uses only the fields it needs
Tools return JSON strings Consistent interface for the LLM to parse; easy to log and debug
Per-agent tool assembly Each agent composes only the tools it needs — keeps prompt token usage minimal
Graceful fallback Agents degrade to single-shot when tool calling is unavailable

MLflow Tracing

All agents are instrumented with MLflow tracing for observability, evaluation, and monitoring. Tracing is initialised at application startup in src/shared/fastapi/main.py and creates spans for:

Span type Decorator Captures
AGENT @trace_agent Full agent run — inputs (excluding secrets), result status, iterations, usage
LLM @trace_llm Each LLM call — endpoint, message count, finish reason, token usage
TOOL @trace_tool Each tool dispatch — tool name, arguments, result length

Configuration

Env Variable Default Description
MLFLOW_TRACKING_URI (none) Set to databricks to persist traces to the workspace tracking server
ONTOBRICKS_MLFLOW_EXPERIMENT ontobricks-agents MLflow experiment name for traces

When MLFLOW_TRACKING_URI=databricks, relative experiment names are automatically resolved to /Shared/<name> so they appear under Machine Learning > Experiments in the Databricks workspace. This is configured in app.yaml for production deployments.

Tracing degrades gracefully: if MLflow is not configured or the tracking server is unreachable, agents run normally without traces.

Tracing module

The shared tracing utilities live in src/agents/tracing.py:

  • setup_tracing(experiment_name) — call once at startup
  • trace_agent(name), trace_llm(name), trace_tool(name) — decorators
  • Secrets (token, host, client) are excluded from span inputs automatically

Databricks Agent Framework Integration

Ontology Assistant — ResponsesAgent

The Ontology Assistant has a wrapper that implements the MLflow ResponsesAgent interface, making it compatible with:

  • AI Playground — test the agent interactively
  • Agent Evaluation — measure quality with LLM judges
  • Model Serving — deploy as a managed endpoint
  • MLflow logging — version and track agent models
Files
File Purpose
src/agents/agent_ontology_assistant/responses_agent.py OntologyAssistantResponsesAgent class
src/agents/agent_ontology_assistant/log_model.py Script to log the agent to MLflow
Usage — In-process (current FastAPI route)
POST /ontology/assistant/invoke
Content-Type: application/json

{
    "input": [
        {"role": "user", "content": "Add an entity called Vehicle"}
    ]
}

The route overwrites custom_inputs with the saved domain LLM target (host, token, endpoint_name, endpoint_kind) and fills ontology context from the active session. Caller-supplied credentials or endpoint names are ignored. If the ontology is modified, the domain is saved.

Usage — Log to MLflow
python -m agents.agent_ontology_assistant.log_model

This creates an MLflow run with the agent model, which can then be registered in Unity Catalog and served via Databricks Model Serving.

Custom inputs / outputs
Field Direction Contents
custom_inputs.host in Databricks workspace URL
custom_inputs.token in Databricks access token
custom_inputs.endpoint_name in AI Gateway FQN or Model Serving endpoint name
custom_inputs.endpoint_kind in ai_gateway or serving (authoritative; do not infer from the name)
custom_inputs.classes in Current ontology classes (list of dicts)
custom_inputs.properties in Current ontology properties (list of dicts)
custom_inputs.base_uri in Ontology base URI
custom_outputs.success out Whether the agent completed successfully
custom_outputs.ontology_changed out Whether any mutations were applied
custom_outputs.classes out Mutated classes (when changed)
custom_outputs.properties out Mutated properties (when changed)

OntoViz - Visual Ontology Editor

OntoViz is a custom JavaScript library for visual entity-relationship diagram editing, integrated into OntoBricks for ontology design. It is reusable and can be integrated into other projects.

Overview

OntoViz provides a visual canvas for creating and managing ontology structures with:

  • Entities (OWL Classes) - Represent concepts in your domain
  • Relationships (OWL Object Properties) - Connect entities with directed links
  • Inheritances (rdfs:subClassOf) - Define class hierarchies with property inheritance

OntoViz Editor


Features

Entity Management

Entities represent ontology classes (owl:Class) and are displayed as interactive boxes on the canvas.

Feature Description
Name Editable entity name (click to edit)
Icon Customizable emoji icon for visual identification
Description Optional text description
Attributes Data properties with name and type
4 Anchors Connection points (top, bottom, left, right) for relationships
Creating Entities
  1. Click the + Add Entity button in the toolbar
  2. A new entity appears on the canvas
  3. Click on the entity name to rename it
  4. Use the + button on the entity to add attributes
  5. Use the 🎨 button to select an icon
  6. Use the 📝 button to add a description
Entity Properties

Each entity can have multiple data properties (attributes):

{
  "id": "entity_123",
  "name": "Person",
  "icon": "👤",
  "description": "Represents a person",
  "properties": [
    { "id": "prop_1", "name": "email", "type": "string" },
    { "id": "prop_2", "name": "age", "type": "integer" }
  ],
  "x": 100,
  "y": 150
}

Relationship Management

Relationships represent object properties (owl:ObjectProperty) that connect entities.

Feature Description
Name Editable relationship name (click on label)
Direction Forward (→), Reverse (←), or Bidirectional (↔︎)
Attributes Optional relationship properties
Visual Solid line with arrow indicating direction
Creating Relationships
  1. Click and drag from one entity's anchor (○) to another entity
  2. A relationship line is created with a label box in the middle
  3. Click the label to rename the relationship
  4. Click the direction button (→/←/↔︎) to change direction
  5. Use the + button on the relationship box to add attributes
Relationship Direction

Each relationship has a direction that controls:

  • Forward (→): Domain → Range (e.g., Person → Department)
  • Reverse (←): Range → Domain (e.g., Department ← Person)
  • Bidirectional (↔︎): Both directions

Click the direction indicator on the relationship box to cycle through options.

Self-Loop Relationships

OntoViz supports recursive relationships (entity linked to itself):

  • Displayed as curved quarter-circle arcs
  • Relationship box can be positioned around the entity
  • Anchors adjust automatically based on box position

Inheritance links represent class hierarchies using rdfs:subClassOf.

Feature Description
Visual Style Dotted line with hollow triangle arrow
Direction From parent class to child class
Property Inheritance Child automatically inherits parent's attributes
Read-Only Inherited Inherited properties shown as non-editable in child
Creating Inheritance
  1. Click the △ Inheritance button in the toolbar to enter inheritance mode
  2. Drag from the parent entity's connector to the child entity
  3. A dotted line with hollow arrow appears
  4. Click the arrow to reverse direction if needed
Property Inheritance

When an inheritance link is created:

  • Child entities automatically display parent's properties
  • Inherited properties are shown with a visual indicator (read-only)
  • Changes to parent properties cascade to all children
  • Children can have additional properties beyond inherited ones

Example:

Person (parent)
├── name: string
└── email: string

Employee (child, inherits from Person)
├── name: string (inherited, read-only)
├── email: string (inherited, read-only)
├── employeeId: string (own property)
└── salary: decimal (own property)

Canvas Controls

Control Action
Scroll Wheel Zoom in/out
Click + Drag (background) Pan the canvas
Click + Drag (entity) Move entity

Toolbar

Button Function
+ Add Entity Create a new entity
△ Inheritance Toggle inheritance creation mode
Grid Layout Auto-arrange entities in a grid
Center Fit all entities in view
Minimap Toggle navigation minimap

Layout Features

Auto-Layout

Click the Grid Layout button to automatically organize entities:

  • Uses force-directed algorithm to minimize overlaps
  • Places connected entities near each other
  • Maintains relationship visibility
Center View

Click Center to:

  • Fit all entities within the visible canvas
  • Auto-zoom to show the complete diagram
  • Useful after loading a large diagram
Minimap

Toggle the minimap for:

  • Overview of the entire diagram
  • Quick navigation to different areas
  • Visual indicator of current viewport

Data Serialization

OntoViz supports JSON import/export for persistence.

Export Format

{
  "entities": [
    {
      "id": "entity_1",
      "name": "Person",
      "icon": "👤",
      "description": "A human being",
      "x": 100,
      "y": 100,
      "properties": [
        { "id": "prop_1", "name": "name", "type": "string" },
        { "id": "prop_2", "name": "email", "type": "string" }
      ]
    },
    {
      "id": "entity_2",
      "name": "Department",
      "icon": "🏢",
      "x": 400,
      "y": 100,
      "properties": [
        { "id": "prop_3", "name": "departmentName", "type": "string" }
      ]
    }
  ],
  "relationships": [
    {
      "id": "rel_1",
      "name": "worksIn",
      "sourceEntityId": "entity_1",
      "targetEntityId": "entity_2",
      "direction": "forward",
      "properties": [
        { "id": "attr_1", "name": "startDate", "type": "date" }
      ]
    }
  ],
  "inheritances": [
    {
      "id": "inh_1",
      "sourceEntityId": "parent_entity_id",
      "targetEntityId": "child_entity_id"
    }
  ],
  "positions": {}
}

Standalone Usage

OntoViz can be used independently of OntoBricks. See the demo at src/front/static/global/ontoviz/index.html.

Basic Integration

<!-- Include OntoViz CSS -->
<link rel="stylesheet" href="ontoviz/css/ontoviz.css">

<!-- Container for the editor -->
<div id="ontoviz-container" style="width: 100%; height: 600px;"></div>

<!-- Include OntoViz JS -->
<script src="ontoviz/ontoviz.js"></script>

<script>
// Initialize OntoViz
const canvas = new OntoViz(document.getElementById('ontoviz-container'), {
    showToolbar: true,
    showMinimap: true,
    snapToGrid: true,
    gridSize: 20
});

// Add entities
const person = canvas.addEntity({ 
    name: 'Person', 
    x: 100, 
    y: 100, 
    icon: '👤',
    properties: [{ name: 'name', type: 'string' }] 
});

const dept = canvas.addEntity({ 
    name: 'Department', 
    x: 400, 
    y: 100, 
    icon: '🏢' 
});

// Add relationship
canvas.addRelationship({ 
    name: 'worksIn',
    sourceEntityId: person.id, 
    targetEntityId: dept.id,
    direction: 'forward'
});

// Export data
const data = canvas.toJSON();
console.log(JSON.stringify(data, null, 2));
</script>

Configuration Options

new OntoViz(container, {
    // Display
    showToolbar: true,      // Show the toolbar
    showMinimap: true,      // Show navigation minimap
    
    // Grid
    snapToGrid: true,       // Snap entities to grid
    gridSize: 20,           // Grid cell size in pixels
    
    // Behavior
    autoLayout: false,      // Auto-layout on load
    readOnly: false,        // Disable editing
    
    // Styling
    defaultEntityIcon: '📦' // Default icon for new entities
});

Event Callbacks

OntoViz provides callbacks for integration with external systems:

new OntoViz(container, {
    // Entity events
    onEntityCreate: (entity) => {
        console.log('Entity created:', entity.name);
    },
    onEntityUpdate: (entity) => {
        console.log('Entity updated:', entity.name);
    },
    onEntityDelete: (entity) => {
        console.log('Entity deleted:', entity.name);
    },
    
    // Relationship events
    onRelationshipCreate: (relationship) => {
        console.log('Relationship created:', relationship.name);
    },
    onRelationshipUpdate: (relationship) => {
        console.log('Relationship updated:', relationship.name);
    },
    onRelationshipDelete: (relationship) => {
        console.log('Relationship deleted:', relationship.name);
    },
    
    // Inheritance events
    onInheritanceCreate: (inheritance) => {
        console.log('Inheritance created');
    },
    onInheritanceDelete: (inheritance) => {
        console.log('Inheritance deleted');
    },
    
    // Selection events
    onSelectionChange: (selection) => {
        console.log('Selection changed:', selection);
    }
});

API Reference

OntoViz Class

Constructor
const canvas = new OntoViz(container, options);
Parameter Type Description
container HTMLElement DOM element to render into
options Object Configuration options
Entity Methods
Method Description
addEntity(options) Create and add a new entity
updateEntity(id, updates) Update entity properties
removeEntity(id) Delete an entity (and its relationships)
getEntity(id) Get entity by ID
getEntities() Get all entities
Relationship Methods
Method Description
addRelationship(options) Create a relationship between entities
updateRelationship(id, updates) Update relationship properties
removeRelationship(id) Delete a relationship
getRelationship(id) Get relationship by ID
getRelationships() Get all relationships
Inheritance Methods
Method Description
addInheritance(options) Create inheritance link
updateInheritance(id, updates) Update inheritance
removeInheritance(id) Delete inheritance link
getInheritedProperties(entityId) Get inherited properties for an entity
Layout Methods
Method Description
autoLayoutGrid(options) Arrange entities in a grid
centerDiagram(options) Center and fit diagram in view
zoomToFit() Zoom to show all content
Serialization Methods
Method Description
toJSON() Export diagram as JSON
fromJSON(data) Import diagram from JSON
clear() Clear all content

OWL Generation

When used with OntoBricks, OntoViz generates W3C-compliant OWL:

Entity → owl:Class

:Person a owl:Class ;
    rdfs:label "Person" ;
    rdfs:comment "A human being" .

:name a owl:DatatypeProperty ;
    rdfs:domain :Person ;
    rdfs:range xsd:string .

Relationship → owl:ObjectProperty

:worksIn a owl:ObjectProperty ;
    rdfs:domain :Person ;
    rdfs:range :Department .

Inheritance → rdfs:subClassOf

:Employee a owl:Class ;
    rdfs:subClassOf :Person ;
    rdfs:label "Employee" .

Naming Conventions

Entity, relationship, and property names must follow these rules:

Rule Description
Characters Letters, numbers, underscores (_), hyphens (-)
No Spaces Use underscores or CamelCase instead
No Symbols Special characters are not allowed
Case Sensitive Person and person are different

Recommended Conventions:

  • Entities: PascalCase (e.g., Person, CustomerOrder)
  • Relationships: camelCase (e.g., worksIn, hasOrder)
  • Properties: camelCase (e.g., firstName, orderDate)

Files Structure

src/front/static/global/ontoviz/
├── ontoviz.js              # Main library code
├── index.html              # Standalone demo page
├── ontoviz_instructions.txt # Feature specifications
└── css/
    ├── ontoviz.css         # Main entry (imports all)
    ├── ontoviz-variables.css # Design tokens / CSS variables
    ├── ontoviz-entity.css  # Entity styling
    ├── ontoviz-relationship.css # Relationship & inheritance styling
    └── ontoviz-ui.css      # UI components (toolbar, minimap)

Theming

OntoViz uses CSS variables for theming. Customize by overriding these variables:

:root {
    /* Entity colors */
    --ontoviz-entity-bg: #ffffff;
    --ontoviz-entity-border: #dee2e6;
    --ontoviz-entity-header-bg: #f8f9fa;
    
    /* Relationship colors */
    --ontoviz-relationship-line: #6c757d;
    --ontoviz-relationship-arrow: #6c757d;
    
    /* Inheritance colors */
    --ontoviz-inheritance-line: #adb5bd;
    
    /* Canvas */
    --ontoviz-canvas-bg: #f5f5f5;
    --ontoviz-grid-color: #e0e0e0;
}

Browser Support

OntoViz works in all modern browsers:

  • Chrome 80+
  • Firefox 75+
  • Safari 13+
  • Edge 80+

No external dependencies required (uses vanilla JavaScript and CSS).


License

OntoViz is part of OntoBricks and is licensed under the Databricks License in the repository root (LICENSE.txt).


See Also


Data access engine map

This document inventories every way the OntoBricks platform reads (or asks the backend to read) data, and pins each user-facing feature to the underlying query engine(s) it ends up using.

The goal is to answer, for any feature in the UI, the MCP server, or the Graph Chat assistant: "when I click this, which engine actually runs?"


1. The five access wrappers

OntoBricks exposes data through five layered wrappers. Three are user-facing languages, two are engine-facing dialects the platform translates down to.

Wrapper Layer Implementation Where the bytes finally land
REST user-facing api/external_app.py, api/routers/..., api/routers/internal/dtwin.py Calls into Python services (DigitalTwin, DomainQueryService, registry, …)
GraphQL user-facing back/core/graphql/GraphQLSchemaBuilder.py, ResolverFactory.py, back/fastapi/graphql_routes.py Resolvers internally call SPARQL / triples-find → Spark SQL
SPARQL user-facing (read-only in chat) back/core/w3c/sparql/SparqlTranslator.py, SparqlQueryRunner.py, DomainQueryService.py Translated to Spark SQL via R2RML mappings
Spark SQL engine-facing back/core/graphdb/delta/DeltaFlatStore.py Native execution on Databricks SQL Warehouse against Delta views in Unity Catalog
Cypher (reserved for future engines) engine-facing back/core/graphdb/GraphDBBackend.py + concrete engines under back/core/graphdb/<engine>/ (supports_cypher = True, query_dialect = "cypher") None of the currently shipped engines speaks Cypher — Lakebase Postgres is SQL-only. The capability flags are kept as a seam for plugging in Cypher / Gremlin / SPARQL-store engines.

Supporting W3C standards (not query languages)

These layers shape queries but don't run them — they are mappings, constraints, and rule definitions:

Standard Role Where
R2RML Maps relational tables → RDF; consumed by SparqlTranslator to lift SPARQL to Spark SQL back/core/w3c/r2rml/
SHACL Constraint validation over RDF (data quality) back/core/w3c/shacl/SHACLService.py
OWL / RDFS Schema definition + entailment (OWLRLReasoner materializes derived triples) back/core/w3c/owl/, back/core/reasoning/OWLRLReasoner.py
SWRL Rule language; compiled to SQL via SWRLSQLTranslator (Spark SQL on Delta, Postgres SQL on Lakebase). The query_dialect flag on GraphDBBackend reserves a slot for a future Cypher translator. back/core/reasoning/SWRL*.py

2. Storage backends — which engine speaks which language

Which engine actually runs your query depends on the domain's configured triple-store backend (GraphDBFactory.create(...)):

Layer Storage Native engine SPARQL path Cypher path
Delta engine (DeltaFlatStore) Delta view in Unity Catalog Spark SQL (Databricks SQL Warehouse) SPARQL → Spark SQL via R2RML n/a
Lakebase engine (LakebaseFlatStore) Lakebase Postgres flat table Postgres SQL SPARQL → engine SQL Reserved for future Cypher engines

The selection is made in back/core/graphdb/GraphDBFactory.py. Both engines share the single GraphDBBackend contract: the Delta view is the governance-controlled snapshot, and the Lakebase engine is the queryable mirror used by the Knowledge Graph, reasoning and BFS / cohort helpers. The user-facing wrappers (REST / GraphQL / SPARQL) don't change when the engine is swapped.

GraphDB engines. GraphDBBackend is the abstract base class; concrete engines live under back/core/graphdb/<engine>/. The currently shipped engine is Lakebase Postgres (back/core/graphdb/lakebase/); additional engines (e.g. KuzuDB, Neo4j, Memgraph) can be plugged in via GraphDBFactory using the _starter_kit/ExampleStore.py template, without changing any of the user-facing wrappers above.


3. Decision tree — which wrapper fires for what?

            "I want to ..."
                  │
        ┌─────────┴──────────────────────────────────────┐
        │                                                │
"... explore / browse / mutate"                "... read graph data"
   the registry, ontology,                              │
   mapping, permissions                                 │
        │                                  ┌────────────┼────────────────┐
        │                                  │            │                │
       REST                              SPARQL      GraphQL          Cypher
   (/api/v1/* or /dtwin/*)            (free-form    (typed,       (graph traversal,
                                       triples,     nested,        SWRL rules)
                                       aggregates,  schema-driven)       │
                                       analytics)                        │
                                                                  Internal only
                                                                 (GraphDB engine
                                                                  + reasoning)

4. UI features — engine map

Pages live under src/front/templates/ and src/front/static/<page>/js/.... Each row maps a UI feature to the wire protocol it speaks (column Wrapper) and the engine that ultimately runs (column Engine).

4.1 Registry & Domain

UI Feature Page / JS file Endpoint(s) Wrapper Engine
Browse / open / create / save domain Registry modal (partials/layout/registry_modal.html), templates/domain.html GET/POST /api/v1/domain/..., /settings/registry/..., /domain/... REST Python services (DomainService, RegistryService); files on UC Volumes
Schedule (background actions) settings (Automation → Scheduler) /settings/schedules, /settings/cohort-schedules REST Python BuildScheduler + Databricks Jobs SDK
Cockpit / readiness domain-validation GET /api/v1/domain/design-status REST Python aggregator over OWL / R2RML / metadata
Data Assets (UC tables / views / metric views preview) domain-metadata Internal REST → databricks-sql-connector REST → Spark SQL Spark SQL on UC tables, views and metric views (sample queries). Each source is tagged with object_kind (table / view / metric_view); metric-view columns also carry a role (dimension / measure) resolved via SHOW CREATE TABLE.
Data source deletion guard domain-metadata POST /domain/metadata/removal-impact REST Mapping.find_mappings_referencing over the session assignment (no warehouse call)
Metadata refresh diff preview domain-metadata POST /domain/metadata/update-async → GET /tasks/{id} REST → Spark SQL compute_column_diff over the pre-merge snapshot; applied only after the user confirms
Knowledge Store upload / status / retry / purge domain-documents.js /domain/documents/upload, /domain/documents/list, /domain/documents/retry-parse REST → Spark SQL parse → Lakebase Parsed text stored in Lakebase domain_documents (no originals kept); one asynchronous inline-base64 ai_parse_document call per changed source hash; 10 MB per-file cap
Versions domain-versions /api/v1/domain/versions REST UC Volume listing

4.2 Ontology Studio

UI Feature JS file Endpoint(s) Wrapper Engine
Visual ontology editor (Model, Entities, Relationships, Groups, Business Views) ontology-design.js, ontology-shared-panels.js, ontology-groups.js Internal REST /ontology/... REST Python ontology object model
OWL viewer / generator ontology-owl.js, agent OWLGenerator /ontology/owl/..., /agents/owl-generator/run REST OntologyParser, OntologyGenerator (rdflib)
Import (OWL, FIBO, CDISC, IOF) ontology-import.js /ontology/import/* REST rdflib parsers
Generate (Wizard) ontology-wizard.js Domain LLM via agent_owl_generator REST → LLM Saved domain LLM: Databricks AI Gateway or Model Serving + tool-calling; selected ready documents come from the shared parsed corpus in the Lakebase Knowledge Store (domain_documents)
AI Assistant Studio floating chat, agent_ontology_assistant POST /ontology/assistant/chat, POST /ontology/assistant/invoke REST → LLM Saved domain LLM (llm_endpoint + llm_endpoint_kind): AI Gateway chat completions or Model Serving invocations
Data Quality rules editor ontology-dataquality.js /ontology/dataquality/... REST SHACL (SHACLService) on the in-memory ontology
Business Rules (SWRL) editor ontology-business-rules.js /ontology/swrl/... REST SWRLParser, validated against ontology
Expressions & Axioms ontology-axioms.js /ontology/axioms/... REST OWL axiom storage

4.3 Mapping (R2RML)

UI Feature JS file Endpoint(s) Wrapper Engine
Mapping designer / manual mapping mapping-design.js, mapping-manual.js /mapping/... REST R2RMLGenerator
Auto-Map (LLM) mapping-autoassign.js, agent AutoAssignment /mapping/auto-assign/... REST → LLM Databricks AI Gateway or FM API; agent samples UC tables via Spark SQL and preloads the same ready parsed-document corpus as Generate
Diagnostics mapping-diagnostics.js /mapping/diagnostics/* REST Python validator
Source schema drift mapping-design.js, mapping-diagnostics.js GET /mapping/schema-drift REST One DESCRIBE per distinct source table via UnityCatalog.get_table_columns
R2RML view mapping-r2rml.js /mapping/r2rml/raw REST rdflib serializer
Spark SQL preview mapping-sparksql.js POST /dtwin/translate REST → SPARQL translation only SparqlTranslator (no execution; shows the generated SQL)

4.4 Knowledge Graph (the core read surface)

This is where users actually query the graph. Explorer, Query (GraphQL and SPARQL), and Graph Chat all sit under the Knowledge Graph menu; they hit different wrappers but eventually share the same Delta / GraphDB storage.

UI Feature JS file Endpoint(s) Wrapper Engine
Insight / Overview query-sync.js (stats panel), query.js GET /dtwin/sync/stats, GET /dtwin/sync/status REST Spark SQL aggregates on the Delta view, or Postgres SQL aggregates on the Lakebase Graph DB
Graph Viewer (Sigma.js viz) query-sigmagraph.js, query-d3graph.js GET /dtwin/groups, POST /dtwin/sync/filter, GET /dtwin/sync/stats?refresh=true, POST /dtwin/clusters/detect, GET /dtwin/reasoning/inferred REST Each /sync/filter call is a SPARQL under the hood, translated to Spark SQL (Delta) or Postgres SQL (Lakebase Graph DB)
Query → SPARQL playground query-execute.js POST /dtwin/execute SPARQL SparqlTranslator → Spark SQL on the SQL Warehouse (Delta view); read-only safety gate blocks update verbs
GraphQL query-graphql.js GET /graphql/{domain}/schema, POST /graphql/{domain}, GET /graphql/settings/depth GraphQL Schema generated from OWL; resolvers call DomainQueryService → SPARQL → Spark SQL
Graph Chat query-chat.js, agent agent_dtwin_chat POST /dtwin/assistant/chat, GET/DELETE /dtwin/assistant/history REST → LLM tool-calling LLM calls REST + GraphQL + SPARQL tools (see §6)
Build (materialize triple store) query-sync.js POST /dtwin/sync/start, POST /dtwin/sync/load REST _BuildPipeline runs the R2RML SQL on the Warehouse (Delta CREATE OR REPLACE VIEW) and streams the rows into the active Graph DB engine via bulk_insert_iter (COPY FROM STDIN on Lakebase)
Data Quality (SHACL execution) query-dataquality.js POST /dtwin/dataquality/start, POST /dtwin/dataquality/execute REST SHACLService translates shapes to SQL SELECTs that find violations
Inference (Reasoning) query-reasoning.js, query-purge-inferences.js POST /dtwin/reasoning/start, POST /dtwin/reasoning/materialize, GET/DELETE /dtwin/reasoning/inferred REST ReasoningService: OWL-RL closure (rdflib) + SWRL rules compiled to SQL (Spark SQL on Delta, Postgres SQL on Lakebase) or SPARQLRuleEngine; GET counts the generated companion shared by reasoning and cohorts, while DELETE truncates only that companion. On Databricks Apps, companion DDL/DML (CREATE, INSERT, TRUNCATE, OPTIMIZE, graph-index rebuild) uses INLINE Statement Execution — the same path as graph reads — because Apps cannot open a Thrift SQL session.
Cockpit → Knowledge Graph domain-validation.js GET /validate/detailed, GET /dtwin/reasoning/inferred REST Displays mapped graph health plus the live combined materialized reasoning-and-cohort count; unsupported source-indistinguishable backends return the count as unavailable

GET /dtwin/reasoning/inferred is a lightweight status call: it returns graph_name, materialized_inference_count, and purge_supported without serializing inferred triples. The nested reasoning.inferred_count and empty reasoning.inferred_triples fields remain for compatibility.

4.5 Settings / Teams / Help

UI Feature Endpoint(s) Wrapper Engine
Settings (warehouse, profile) /settings/* REST Python config service
Teams (domain roles) /settings/teams REST PermissionService + App ACL principals
Help / docs modal static templates n/a n/a

5. MCP server (src/mcp-server) — engine map

The MCP server is a thin proxy over the OntoBricks public REST + GraphQL surface (/api/v1/... and /graphql/...). It runs as its own Databricks App, authenticates with an M2M OAuth token, and uses httpx.AsyncClient. It never speaks SPARQL or Cypher directly.

Since v0.9.0 the MCP server also forwards the end-user identity: it captures the inbound x-forwarded-email / x-forwarded-access-token per tool call and attaches them alongside the M2M Authorization on every outbound request, so the main app applies OBO (Unity Catalog reads run as the user) and the Team gate (Viewer+ membership for Lakebase/Neo4j reads) to MCP-driven traffic. Data-plane routes are fail-closed when no user token is forwarded.

MCP Tool Endpoint hit Wrapper Engine
list_domains GET /api/v1/domains REST UC Volume listing
list_domain_versions GET /api/v1/domain/versions REST UC Volume listing
get_design_status GET /api/v1/domain/design-status REST Python aggregator
describe_ontology GET /api/v1/domain/ontology + GET /api/v1/domain/classes REST Ontology schema only (no graph): structured class summary + raw OWL/Turtle
select_domain GET /api/v1/digitaltwin/status + GET /api/v1/domain/classes REST DeltaFlatStore status (Spark SQL) or GraphDB status; class attachments cached for [Context] blocks
list_entity_types GET /api/v1/digitaltwin/stats REST Spark SQL GROUP BY on the triple view (Delta) or GraphDB MATCH counts
describe_entity GET /api/v1/digitaltwin/triples/find REST SPARQL-style BFS internally → Spark SQL (Delta) or Cypher (GraphDB)
get_entity_context GET /api/v1/digitaltwin/nodes/context REST Class resolution + optional Spark SQL dataset read and bridge traversal
compute_virtual_attributes GET /api/v1/digitaltwin/nodes/virtual-attributes REST Unity Catalog function call for declared virtual attributes
invoke_entity_action POST /api/v1/digitaltwin/nodes/action REST Unity Catalog function via SQL warehouse, or Databricks Job run_now (job:<id>) tracked in TaskManager
run_entity_business_rule POST /api/v1/digitaltwin/nodes/business-rule REST SWRL rule → entity-scoped Spark SQL inference + insert into the graph (Builder role required)
check_entity_shacl_facets GET /api/v1/digitaltwin/nodes/shacl REST Applicable SHACL shapes (class + ancestors + global) → one entity-scoped UNION ALL Spark SQL batch, per-shape fallback on error
get_status GET /api/v1/digitaltwin/status REST Same as select_domain
get_graphql_schema GET /graphql/{domain}/schema GraphQL GraphQLSchemaBuilder (no DB hit; SDL only)
query_graphql POST /graphql/{domain} GraphQL Resolvers → SPARQL → Spark SQL
ontobricks://* resources various REST / GraphQL Same as the equivalent tools

Per-domain policy. The first three tools are registry-level and always available. The rest are domain-scoped: a domain can hide any of them from Domain → Information → MCP, and can set its dataset / bridges / actions attachments to disabled. Because the MCP server is a proxy, the disabling is enforced at the endpoints above, not in the proxy — nodes/context and domain/classes omit the element, and nodes/action refuses. Hiding a tool is presentation on top of that, so a stale client that calls a hidden tool anyway gets a refusal instead of data. See Per-domain MCP policy.

Ontology-only domains. A domain can be published with an ontology but no Knowledge Graph build (no mapping, no graph). GET /api/v1/domains flags it with has_graph: false; on select_domain the MCP server hides every graph tool and exposes describe_ontology alone (plus the four registry-level tools). describe_ontology needs no graph — it serves the ontology schema — so it is always available and the call-time guard refuses the graph tools for such a domain even if a stale client calls them.

Note. MCP and the external REST/GraphQL API only see versions whose lifecycle status is PUBLISHED — they default to the numeric-latest PUBLISHED version and reject explicit requests for DRAFT/IN-REVIEW versions. A version becomes servable by transitioning it DRAFT → IN-REVIEW → PUBLISHED from Registry → Browse (this replaces the former "Active"/mcp_enabled toggle). To query an unsaved working session, use the Graph Chat (next section), which talks to the session-aware /dtwin/... internal routes instead.


6. Graph Chat (src/agents/agent_dtwin_chat) — engine map

The Graph Chat agent runs inside the OntoBricks process, talks to loopback (http://localhost:8000), forwards user session cookies + the Databricks Apps X-Forwarded-* headers, and targets the internal session-aware /dtwin/... routes. This means it works on unsaved domains and (uniquely) speaks SPARQL.

Chat Tool Endpoint hit Wrapper Engine
list_entity_types GET /dtwin/sync/stats REST Spark SQL stats (Delta) or GraphDB stats
get_status GET /dtwin/sync/status REST Triple store status
describe_entity GET /dtwin/triples/find REST Bounded BFS → Spark SQL (Delta) or Cypher (GraphDB)
get_graphql_schema GET /dtwin/graphql/schema GraphQL Schema built from in-session ontology (no DB)
query_graphql POST /dtwin/graphql/execute GraphQL Resolvers → SPARQL → Spark SQL
run_sparql POST /dtwin/execute SPARQL (read-only — DROP/DELETE/INSERT/CREATE/CLEAR/LOAD/COPY/MOVE/ADD blocked by regex) SparqlQueryRunner → Spark SQL on the SQL Warehouse

The system prompt steers the LLM's protocol choice:

  • "Tell me about X" → describe_entity (REST/triples)
  • "How many / group by / aggregate" → run_sparql (SPARQL → Spark SQL)
  • "Customer + orders + products in one payload" → get_graphql_schema then query_graphql

7. Other LLM agents — engine map

These agents do not query the triple store at runtime; they operate on the design-time ontology / metadata.

Agent Purpose Tools call Wrapper Engine
agent_owl_generator Build an OWL ontology from metadata + documents metadata.list_tables, metadata.preview_table, documents.read, ontology.write_owl REST + Spark SQL (samples) databricks-sql-connector against UC tables, plus rdflib write
agent_auto_assignment Map ontology entities to Spark SQL queries tables.list, tables.sample, mapping.write REST + Spark SQL (samples) Same as above; output stored as R2RML. Metric-view sources (object_kind == "metric_view") drive metric-aware generation — measures are wrapped in MEASURE() and a GROUP BY over dimensions is emitted; a deterministic evaluator rejects SELECT *, unwrapped measures, or a missing GROUP BY.
agent_auto_icon_assign Pick emojis for entities Inspects ontology + metadata REST None — generation only
agent_ontology_assistant Conversational ontology editing Dozens of tools mutating the in-session ontology REST Python ontology object model
agent_dtwin_chat Conversational graph querying See §6 REST + GraphQL + SPARQL Spark SQL + Cypher (engine-side)

Document reading (documents.read / read_document)

Both agent_owl_generator and agent_business_rules_generator read the parsed text of domain documents from the Lakebase Knowledge Store (domain_documents) via read_document — the original binary is never stored, so there is nothing to re-read from a Volume:

  • Documents are parsed once, at upload time, and only their parsed text is persisted. read_document returns that stored parsed text directly from Lakebase.
  • Parsing uses the Databricks ai_parse_document SQL function with the uploaded bytes passed inline as base64 (output schema pinned to v2.0): SELECT to_json(ai_parse_document(unbase64('<base64>'), map('version', '2.0'))) AS parsed. This runs on the configured SQL warehouse. Because the bytes are inlined, it no longer reads from a Volume path / READ_FILES, so no READ VOLUME grant is required. A hard 10 MB per-file cap applies (base64 inflation against the Statement Execution API's ~16 MiB limit). The function returns a VARIANT (output schema v2.0, verified live): text is read from document.elements[].content (figures expose an AI-generated description); document.pages[] only carries id/image_uri. The extractor prefers elements and keeps page-content / markdown-blob fallbacks for other schema versions. The extraction engine is a generic, reusable class — back.core.databricks.document.DocumentExtractor (src/back/core/databricks/document/DocumentExtractor.py, exposing supports() / is_available() / extract() / extract_text_from_parsed()) — so it can be used outside the agents and swapped for a different parser without changing callers.
  • Parsing requires a SQL warehouse at upload time; documents that could not be parsed (e.g. no warehouse configured, or parse failure) stay in a failed state and are skipped, so generation proceeds from metadata + the successfully parsed documents only. At agent runtime read_document just returns the stored parsed text (truncated to the per-document character cap).

8. Reasoning engine — engine map

The reasoning pipeline (back/core/reasoning/) chooses a translation target based on the active triple-store backend's query_dialect.

Component Input Compiled to Engine
OWLRLReasoner OWL 2 RL fragment + facts RDF graph operations (rdflib) Python in-memory; results materialized to triple store via Spark SQL or GraphDB bulk insert
SWRLEngine + SWRLSQLTranslator SWRL rules SQL Databricks SQL Warehouse on the Delta view, and the Lakebase Postgres Graph DB engine. Future Cypher / Gremlin engines can plug in their own SWRL*Translator.
SPARQLRuleEngine SPARQL CONSTRUCT rules SPARQL → Spark SQL Same as SPARQL execution path
DecisionTableEngine Decision tables Spark SQL Databricks SQL Warehouse
AggregateRuleEngine Aggregate rules Spark SQL Databricks SQL Warehouse

9. Three end-to-end query flows

9.1 User clicks Graph Chat → "How many Customers per Country?"

Browser  ──POST /dtwin/assistant/chat──▶  api/routers/internal/dtwin.py
                                                  │
                                                  ▼
                                       agent_dtwin_chat.engine.run_agent
                                                  │
                                                  │ tool_call: run_sparql
                                                  ▼
                          POST /dtwin/execute  (loopback HTTP, session cookies)
                                                  │
                                                  ▼
                                  SparqlTranslator (SPARQL → Spark SQL via R2RML)
                                                  │
                                                  ▼
                                  Databricks SQL Warehouse on Delta view
                                                  │
                                                  ▼
                                       rows → markdown table → reply

Wrappers in play: REST → SPARQL → Spark SQL.

9.2 External LLM (Cursor) calls MCP query_graphql

Cursor (stdio)  ──FastMCP──▶  src/mcp-server/server/app.py
                                       │
                                       ▼
                       POST /graphql/{domain}  (httpx, M2M OAuth bearer)
                                       │
                                       ▼
                    back/fastapi/graphql_routes.py → ResolverFactory
                                       │
                                       ▼
                              DomainQueryService (SPARQL)
                                       │
                                       ▼
                       Databricks SQL Warehouse on Delta view

Wrappers in play: REST (transport) → GraphQL (query) → SPARQL → Spark SQL.

9.3 User opens Graph Viewer tab and applies a filter

Browser  ──POST /dtwin/sync/filter──▶  api/routers/internal/dtwin.py
                                                │
                                                ▼
                                        DigitalTwin.filter()
                                                │
                                                │   backend = "view"          backend = "graph"
                                                ▼                                    ▼
                                  SparqlTranslator             GraphDBBackend.query(...)
                                  (SPARQL → Spark SQL)         (e.g. Lakebase Postgres)
                                                │                            │
                                                ▼                            ▼
                              Databricks SQL Warehouse           Lakebase flat table
                                                                  (Postgres SQL)
                                                │                            │
                                                └──────► triples ◀───────────┘
                                                            │
                                                            ▼
                                              Sigma.js renders the graph

Wrappers in play: REST → (SPARQL → Spark SQL on Delta) and Postgres SQL on the Lakebase Graph DB.


10. TL;DR matrix — what each surface exposes

Surface REST GraphQL SPARQL Spark SQL (Delta) Postgres SQL (Lakebase)
UI — Registry / Domain / Ontology / Mapping ✓ sample-only
UI — Graph Viewer (Sigma) ✓ (via filter) ✓ ✓
UI — SPARQL panel ✓ ✓
UI — GraphQL tab ✓ (under) ✓
UI — Graph Chat ✓ ✓ ✓ ✓ ✓
UI — Inference ✓ (SPARQLRuleEngine) ✓ ✓
UI — Data Quality (SHACL) ✓ ✓ ✓
MCP server ✓ ✓ ✓ ✓
Graph Chat agent ✓ ✓ ✓ ✓ ✓
Other agents (OWL gen, auto-map, …) ✓ ✓ (sampling UC)

User-visible query languages today: REST, GraphQL, SPARQL. Engine-side dialects the platform compiles down to: Spark SQL on the Delta view and Postgres SQL on the Lakebase Graph DB. The query_dialect flag on GraphDBBackend reserves a slot for plugging in a future Cypher / Gremlin engine.


  • REST routes — src/api/routers/internal/dtwin.py, src/api/routers/v1.py, src/api/external_app.py
  • GraphQL — src/back/fastapi/graphql_routes.py, src/back/core/graphql/{GraphQLSchemaBuilder,ResolverFactory,SchemaMetadata}.py
  • SPARQL — src/back/core/w3c/sparql/{SparqlTranslator,SparqlQueryRunner,DomainQueryService}.py
  • Graph DB factory — src/back/core/graphdb/GraphDBFactory.py
  • GraphDB backend — src/back/core/graphdb/GraphDBBackend.py
  • Delta engine — src/back/core/graphdb/delta/DeltaFlatStore.py
  • GraphDB engine (Lakebase Postgres) — src/back/core/graphdb/lakebase/{LakebaseBase,LakebaseFlatStore,SyncedTableManager}.py
  • Reasoning — src/back/core/reasoning/{OWLRLReasoner,SWRLSQLTranslator,SPARQLRuleEngine,DecisionTableEngine,AggregateRuleEngine}.py
  • MCP server — src/mcp-server/server/app.py, src/mcp-server/mcp_server.py
  • Graph Chat — src/agents/agent_dtwin_chat/{engine,tools}.py