# How Knowledge Graph Schema Validation Works in Understand-Anything: The 4-Stage Pipeline

> Discover how Understand Anything validates knowledge graphs with a 4-stage pipeline: sanitization, alias normalization, auto-fixing, and strict validation for schema conformity.

- Repository: [Egonex/Understand-Anything](https://github.com/Egonex-AI/Understand-Anything)
- Tags: deep-dive
- Published: 2026-06-20

---

**Schema validation in Understand-Anything runs a four-tier pipeline—sanitization, alias normalization, auto-fixing, and strict validation—to ensure every knowledge graph conforms to the canonical schema before reaching the dashboard.**

When loading a knowledge graph in the Egonex AI Understand-Anything platform, the system enforces strict **schema validation** to prevent malformed data from reaching the visualization layer. The validation logic lives in [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts) and implements a defensive pipeline that sanitizes, normalizes, and auto-corrects LLM-generated graph data while isolating fatal errors from recoverable issues.

## The Four-Stage Validation Pipeline

The core `validateGraph` function orchestrates four sequential transformations defined in [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts). Each stage prepares the raw JSON for final strict validation while accumulating diagnostic metadata.

### Stage 1: Sanitization with `sanitizeGraph`

The pipeline begins with `sanitizeGraph` (lines 48–94), which normalizes null values, lower-cases enum-like strings, and strips empty optional fields. This defensive first pass ensures that downstream validators receive predictable data types and consistent casing, preventing common LLM output inconsistencies from triggering false validation errors.

### Stage 2: Alias Normalization with `normalizeGraph`

Next, `normalizeGraph` (lines 68–80) replaces LLM-generated aliases with canonical enum values. For example, the string `"func"` is mapped to the standard `"function"` type. This stage ensures that semantic variations in the source data resolve to the strict vocabulary defined in the core schema.

### Stage 3: Auto-Fixing and Coercion with `autoFixGraph`

The third stage, `autoFixGraph` (lines 96–150), supplies sensible defaults for missing fields and coerces incompatible types. If a node lacks a type, the function injects the default `"file"`. If an edge lacks a weight, it assigns `0.5`. Simultaneously, it accumulates a list of non-fatal issues—such as coerced strings converted to numbers—allowing the pipeline to continue while flagging corrections for user review.

### Stage 4: Strict Validation with `validateGraph`

The final stage performs destructive validation that drops invalid entries. After invoking the previous sanitization and auto-fix steps, `validateGraph` executes several critical checks:

- **Root Structure Validation**: Verifies that top-level collections are arrays, returning a fatal error if this check fails (lines 118–121).
- **Metadata Validation**: Parses the project metadata against `ProjectMetaSchema` (lines 332–338).
- **Node Validation**: Validates each entry against `GraphNodeSchema`; invalid nodes are dropped and recorded in the `issues` array (lines 443–456).
- **Edge Integrity**: Validates edges against `GraphEdgeSchema` and ensures that `source` and `target` IDs exist in the validated node set; dangling edges are removed and reported (lines 470–506).
- **Layer and Tour Cleanup**: Validates layers and tour steps, stripping any dangling references that point to removed nodes or edges (lines 511–540).

## Handling Validation Results

The `validateGraph` function returns a discriminated union that distinguishes between fatal failures and successful validation with warnings. If any fatal condition occurs—such as the root object not being an object, missing project metadata, or zero valid nodes remaining after filtering—the function returns `success: false` alongside a `fatal` message string.

When validation succeeds, the function returns `success: true`, the fully sanitized and auto-fixed graph data, and an `issues` array containing non-fatal corrections. This design allows the dashboard to load partial graphs while surfacing specific problems to the user.

## Practical Implementation Example

To validate a knowledge graph JSON file in your own tooling, import the core validator and invoke it on the parsed data:

```typescript
import { validateGraph } from "@understand-anything/core";

// Load a JSON file generated by the analyzer
const rawGraph = await fetch("/file-content.json").then(r => r.json());

// Run the full validation pipeline
const result = validateGraph(rawGraph);

if (result.success) {
  console.log("✅ Graph is valid");
  // Use the clean data for dashboard rendering
  const graph = result.data!;
} else {
  console.error("❌ Graph validation failed:", result.fatal);
  console.warn("Issues discovered:", result.issues);
}

```

The Understand-Anything dashboard invokes this same function when loading a project's [`.understand-anything/knowledge-graph.json`](https://github.com/Egonex-AI/Understand-Anything/blob/main/.understand-anything/knowledge-graph.json) file, ensuring that only well-typed, referentially intact graphs reach the UI layer.

## Summary

- **Four-stage pipeline**: Sanitization → alias normalization → auto-fixing → strict validation.
- **Destructive filtering**: Invalid nodes and dangling edges are dropped during strict validation, while valid data proceeds to the dashboard.
- **Default injection**: The auto-fixing stage supplies default node types (`"file"`) and edge weights (`0.5`) to maximize graph usability.
- **Fatal vs. non-fatal**: Fatal errors halt processing immediately, whereas non-fatal issues are collected and returned alongside valid data.
- **Single source of truth**: All validation logic resides in [`packages/core/src/schema.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/packages/core/src/schema.ts), referenced by both the core package and the dashboard server.

## Frequently Asked Questions

### What happens if a node fails validation in Understand-Anything?

Invalid nodes are dropped from the graph during the strict validation phase. The `validateGraph` function filters each node against `GraphNodeSchema` (lines 443–456), removes those that fail, and records the specific validation errors in the returned `issues` array. The pipeline continues processing remaining valid nodes and edges.

### Does the schema validator automatically fix missing edge weights?

Yes. The `autoFixGraph` function (lines 96–150) automatically assigns a default weight of `0.5` to any edge that lacks this property. It also coerces string values to numbers where necessary, accumulating these corrections as non-fatal issues that can be reviewed by the user.

### How does the validator handle LLM-generated type aliases like "func"?

During the alias normalization stage, `normalizeGraph` (lines 68–80) maps LLM-generated aliases to canonical enum values. For example, `"func"` is normalized to `"function"`. This ensures that semantic variations in AI-generated code maps conform to the strict vocabulary required by the `GraphNodeSchema`.

### Can the dashboard load a graph if the project metadata is missing?

No. Missing project metadata triggers a fatal error. The validator checks the top-level metadata against `ProjectMetaSchema` (lines 332–338), and if this required block is absent or malformed, `validateGraph` returns `success: false` with a descriptive fatal message, preventing the dashboard from loading an incomplete graph.