# How to Debug Graph Validation Errors and Schema Violations in Understand-Anything

> Learn to debug graph validation errors and schema violations in Understand-Anything. This guide helps you fix issues and ensure data integrity in your Lum1104 project.

- Repository: [Yuxiang Lin/Understand-Anything](https://github.com/Lum1104/Understand-Anything)
- Tags: how-to-guide
- Published: 2026-05-22

---

**The validation pipeline in Understand-Anything sanitizes input, auto-fixes common issues, and validates against Zod schemas, recording recoverable issues as GraphIssues while aborting on fatal errors.**

Understand-Anything constructs knowledge graphs that map code, configuration, and documentation relationships. When persisting these graphs, the system enforces strict schema compliance through a validation pipeline defined in [`packages/core/src/schema.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/packages/core/src/schema.ts). Mastering **debugging graph validation errors and schema violations** ensures your knowledge graphs persist correctly and render properly in the dashboard.

## The Three-Stage Validation Pipeline

The validation logic in [`packages/core/src/schema.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/packages/core/src/schema.ts) processes raw graph data through three distinct phases before persistence.

### Sanitization and Normalization

The first stage normalizes loosely-typed input. Null values convert to empty arrays, strings are lower-cased, and basic type coercion prepares the data for strict validation.

### Auto-Fixing Missing Fields

The `autoFixGraph` function (lines 96-210 in [`schema.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/schema.ts)) supplies default values for missing fields. It assigns `type: "file"` when node types are missing, clamps numeric weights to the `[0, 1]` range, and maps common aliases to canonical names using `NODE_TYPE_ALIASES` and `EDGE_TYPE_ALIASES`.

### Zod Schema Enforcement

Finally, `validateGraph` (line 499) checks every node, edge, layer, and tour step against `GraphNodeSchema` and `GraphEdgeSchema`. These Zod objects enforce that nodes use one of 21 allowed types and edges use one of 35 canonical edge types defined in `EdgeTypeSchema`.

## Common Graph Validation Errors and Schema Violations

When troubleshooting validation failures, these patterns appear most frequently:

**Missing Required Collections**

If `nodes`, `edges`, `layers`, or `tour` are missing or not arrays, validation returns a fatal `"invalid-collection"` error. Always ensure these keys exist as arrays, even if empty (`"nodes": []`).

**Invalid Node Types**

Nodes with `type` values outside the 21 canonical types trigger `"invalid-node"` issues. The validator drops these nodes unless you use recognized aliases like `func` → `function` or `pkg` → `package` defined in `NODE_TYPE_ALIASES`.

**Invalid Edge Types**

Edges must match one of the 35 types in `EdgeTypeSchema` (such as `imports`, `calls`, or `defines_schema`). Unrecognized types generate `"invalid-edge"` issues.

**Weight Out of Range**

Edge weights outside `[0, 1]` are auto-corrected with an `"out-of-range"` issue logged. The system clamps values rather than failing.

**Missing Project Metadata**

The `project` object requires specific fields (`name`, `languages`, etc.) per `ProjectMetaSchema`. Absence triggers a fatal error: `"Missing or invalid project metadata"`.

**Reference Integrity Violations**

Edges pointing to non-existent node IDs cause `"invalid-reference"` errors. The validator drops these edges and reports the specific path (e.g., `edges[2].target`).

## Step-by-Step Debugging Workflow

Follow this systematic approach when resolving validation failures:

1. **Execute validation and inspect the result.** Import `validateGraph` from `@understand-anything/core/schema` and call it with your graph object. Check `result.fatal` for abort conditions and `result.issues` for auto-corrected or dropped items.

2. **Locate the offending path.** Each `GraphIssue` includes a `path` property (e.g., `nodes[3].type`). Search your source JSON at this exact location to identify malformed data.

3. **Apply corrections.** Add missing required fields, replace invalid aliases with canonical values from the alias maps, or fix broken node ID references.

4. **Re-validate.** Confirm `result.success` is `true` and the `issues` array contains only acceptable auto-corrections.

5. **Persist through the storage layer.** Write the validated graph using the persistence layer in [`packages/core/src/persistence/index.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/packages/core/src/persistence/index.ts), which automatically runs validation before saving.

## Practical Code Examples

### Validating Graphs Programmatically

Wrap the validation logic to catch fatal errors before persistence:

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

export function assertValidGraph(graph: unknown) {
  const result = validateGraph(graph);
  if (!result.success) {
    throw new Error(
      `Graph validation failed – ${result.fatal ?? "unknown error"}\n` +
      `Issues:\n${result.issues.map((i) => `- ${i.message}`).join("\n")}`
    );
  }
  return result.data; // clean, typed graph
}

```

This uses the `validateGraph` implementation from [`packages/core/src/schema.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/packages/core/src/schema.ts) at line 499.

### Auto-Fixing Raw JSON Files

Process existing graph files to apply automatic corrections:

```typescript
import { readFileSync, writeFileSync } from "fs";
import { validateGraph } from "@understand-anything/core/schema";

const raw = JSON.parse(readFileSync("graph.json", "utf-8"));
const { data, issues } = validateGraph(raw);

console.log("Auto-fixed issues:", issues);
writeFileSync("graph-fixed.json", JSON.stringify(data, null, 2));

```

The `autoFixGraph` function (lines 96-210) handles missing type defaults and weight clamping automatically.

### Debugging Specific Edge Failures

Isolate and inspect problematic edges:

```typescript
import type { GraphEdge } from "@understand-anything/core/types";

function findBadEdges(graph: any) {
  const result = validateGraph(graph);
  const badEdges = result.issues.filter((i) => i.category === "invalid-edge");
  
  if (badEdges.length) {
    console.warn("Invalid edges found:", badEdges);
    // Each issue contains the path, e.g., "edges[5].type"
  }
}

```

### Extending the Schema with Custom Types

To add non-standard node types, modify the Zod enumeration in [`schema.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/schema.ts):

```typescript
// In packages/core/src/schema.ts
type: z.enum([
  "file", "function", "class", "module", "concept",
  "config", "document", "service", "table", "endpoint",
  "pipeline", "schema", "resource", "domain", "flow", 
  "step", "article", "entity", "topic", "claim", "source",
  "widget" // <-- new custom type
]),

```

Then register an alias:

```typescript
NODE_TYPE_ALIASES["wdg"] = "widget";

```

## Key Source Files for Troubleshooting

| File | Purpose |
|------|---------|
| [`packages/core/src/schema.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/packages/core/src/schema.ts) | Central schema definitions, `validateGraph`, and `autoFixGraph` logic. |
| [`packages/core/src/types.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/packages/core/src/types.ts) | TypeScript types mirroring Zod schemas (e.g., `KnowledgeGraph`, `GraphIssue`). |
| [`packages/core/src/persistence/index.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/packages/core/src/persistence/index.ts) | Persistence layer that calls validation before writing to disk. |
| [`packages/core/src/__tests__/schema.test.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/packages/core/src/__tests__/schema.test.ts) | Test suite documenting validation behavior for edge cases. |

## Summary

- The validation pipeline runs sanitization, auto-fixing via `autoFixGraph`, and Zod schema checks in sequence.
- Fatal errors abort processing, while recoverable issues are recorded as `GraphIssue` objects with detailed paths.
- Common fixes include ensuring arrays for required collections, using canonical node/edge types or their aliases, and clamping weights to `[0, 1]`.
- Reference [`packages/core/src/schema.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/packages/core/src/schema.ts) (lines 96-210, 499) for validation logic and [`packages/core/src/persistence/index.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/packages/core/src/persistence/index.ts) for persistence integration.

## Frequently Asked Questions

### What is the difference between fatal errors and recoverable issues?

Fatal errors, such as missing required collections like `nodes` or invalid project metadata, abort the validation process immediately and prevent persistence. Recoverable issues include auto-corrected values (like clamped weights) or dropped invalid nodes/edges; these allow the validation to complete and return cleaned data alongside the issue log.

### How do I resolve "invalid-node" errors without manually editing large JSON files?

Use the alias system defined in `NODE_TYPE_ALIASES`. Ensure your graph generation logic outputs aliases like `func` instead of misspellings, or modify the source analyzer to produce canonical types. The auto-fixer will also apply defaults (setting missing types to `"file"`), but explicit correct types prevent data loss.

### Why are my edges being dropped with "invalid-reference" errors?

This occurs when an edge's `source` or `target` property contains a node ID that does not exist in the `nodes` collection. Verify that all edge references match actual node IDs in your graph. The validation error includes the exact path (e.g., `edges[2].target`), allowing you to pinpoint the broken reference.

### Can I disable schema validation during development?

While not recommended, you can bypass the persistence layer's validation by manipulating the graph data structure directly. However, the dashboard and other consumers expect valid graphs per `GraphNodeSchema` and `GraphEdgeSchema`. Disabling validation risks runtime errors in [`packages/dashboard/src/store.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/packages/dashboard/src/store.ts) and layout failures in [`packages/dashboard/src/utils/elk-layout.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/packages/dashboard/src/utils/elk-layout.ts).