Schedule icon
Query icon
OutputValues icon
Switch icon
Write icon
If icon
Log icon
SlackIncomingWebhook icon

Neo4j DAG Cycle Breach and Hierarchy Integrity Gate

Audit Neo4j graphs for hierarchy DAG cycle breaches, generate audit certificates, sever culprit closing edges, and alert engineering on circular references.

Categories
Data

Hierarchical graphs modeled in Neo4j, such as role-based access control (RBAC) inheritance structures, organizational reporting lines, task dependency networks, and manufacturing bills of materials (BOM), strictly depend on the Directed Acyclic Graph (DAG) mathematical invariant. Upstream batch data syncs, asynchronous event streams, or manual admin edits frequently introduce accidental circular dependencies (e.g., node A -> node B -> node C -> node A). When downstream services or analytical pipelines execute recursive Cypher traversals (such as MATCH (r)-[:INHERITS*]->(p)), these circular references trigger unbounded iterations, transaction timeouts, thread pool starvation, and catastrophic Java Virtual Machine Out-Of-Memory (OOM) cluster crashes.

This blueprint provides an automated, production-grade integrity gate for Neo4j hierarchies. It executes variable-length Cypher cycle detection queries using path isomorphism constraints, produces an immutable audit certificate in Kestra internal storage, alerts platform teams via Slack with exact cyclic traces, and conditionally severs the culprit closing back-edge while preserving legitimate hierarchy nodes and parent branches.

How it works

  1. Trigger and Scheduled Evaluation: Runs on an automated daily schedule at 04:00 UTC via io.kestra.plugin.core.trigger.Schedule, or on demand after batch ETL syncs via manual invocation or webhook.
  2. Variable-Length Cycle Discovery: Task detect_cycles (io.kestra.plugin.neo4j.Query) evaluates paths of depth 1..max_search_depth where start node equals end node. An interior node constraint (WHERE all(m IN nodes(path)[1..-1] WHERE elementId(m) > elementId(n))) guarantees that each distinct directed cycle is returned exactly once anchored at its minimal node ID, preventing duplicate counting.
  3. Integrity Metric Classification: Task evaluate_integrity (io.kestra.plugin.core.output.OutputValues) computes the total count of cycles detected, identifies the shortest cycle length, extracts closing relationship element IDs, and sets the routing status to either CYCLE_BREACH or DAG_VALID.
  4. Conditional Routing: Task route_integrity_verdict (io.kestra.plugin.core.flow.Switch) inspects the integrity verdict:
    • CYCLE_BREACH:
      • generate_audit_certificate (io.kestra.plugin.core.storage.Write) persists an immutable JSON audit certificate into Kestra internal storage recording the timestamp, audited labels, cycle count, and complete path traces.
      • check_remediation_gate (io.kestra.plugin.core.flow.If) validates whether auto_sever_cycle is set to "true" and dry_run is set to "false". If enabled, task sever_culprit_closing_edges (io.kestra.plugin.neo4j.Query) safely deletes only the closing back-edges identified in the audit certificate, leaving all entities intact. Next, verify_dag_restored re-audits the graph to confirm DAG restoration.
      • alert_cycle_breach_slack (io.kestra.plugin.slack.notifications.SlackIncomingWebhook) dispatches a high-priority incident notification to Slack with cycle metrics and storage URI.
    • DAG_VALID:
      • log_dag_healthy (io.kestra.plugin.core.log.Log) logs confirmation that zero cycles were detected across the hierarchy.
  5. Failure Safeguard: The errors handler captures driver connection timeouts or authentication failures and posts an urgent Slack notification to on-call data engineers.

What you get

  • Automated DAG Invariant Enforcement: Proactively detects circular hierarchy references before recursive analytical queries fail or trigger JVM heap exhaustion.
  • Safe Back-Edge Remediation: Eliminates cycles by deleting only the specific closing edge that formed the loop, preserving all existing node properties and valid ancestor paths.
  • Immutable JSON Audit Certificates: Retains structured forensic records of all cycle incidents in Kestra internal storage for compliance and root-cause analysis.
  • Dry-Run Protection: Defaults to dry-run mode (dry_run: "true", auto_sever_cycle: "false"), guaranteeing no destructive relationship mutations occur without explicit administrative authorization.
  • Dual-Mode Alerting: Sends Slack incident alerts on cycle detection and pipeline failures.

Who it's for

  • Graph Database Administrators & Platform Engineers: Responsible for Neo4j cluster stability, heap health, and preventing runaway recursive query saturation.
  • Data Platform & Analytics Engineers: Maintaining master data management (MDM) hierarchies, RBAC role assignment graphs, and dependency models.
  • Data Governance & Compliance Teams: Enforcing organizational hierarchy integrity and auditing structural relationship anomalies.

Why orchestrate this with Kestra

Detecting and remediating graph cycles through one-off shell scripts or isolated cron jobs creates visibility blind spots: scripts fail silently on network blips, lack audit trails of severed relationships, and expose database credentials.

Orchestrating this process with Kestra delivers:

  • Declarative Hierarchy Governance: Model the complete audit, certificate generation, conditional remediation, and notification flow as version-controlled YAML.
  • Granular Execution Lineage: Inspect the Gantt chart to review exact Cypher query timings, row counts, and decision branches.
  • Internal Storage Integration: Store forensic JSON certificates directly in Kestra internal storage without requiring external S3 or Blob storage buckets.
  • Secure Credential Masking: Protect Neo4j basic-auth credentials and Slack webhooks using native Kestra secret management ({{ secret('NAME') }}).

Prerequisites

  • A running Neo4j 5.x instance (Community or Enterprise edition, self-hosted or Dockerized).
  • Network connectivity from the Kestra worker to the Neo4j Bolt port (bolt://localhost:7687).
  • Read and write permissions on the target Neo4j database if automatic remediation is enabled.
  • An incoming Slack webhook URL for operational alerting.

Secrets

  • NEO4J_USERNAME: Neo4j database user with query and relationship delete privileges (e.g., neo4j).
  • NEO4J_PASSWORD: Password for the Neo4j database user.
  • SLACK_WEBHOOK_URL: Slack Incoming Webhook URL for posting integrity incident alerts.

Quick start

  1. Deploy a local Neo4j instance for testing:
    docker run -d --name neo4j-test \
      -p 7474:7474 -p 7687:7687 \
      -e NEO4J_AUTH=neo4j/testpassword123 \
      neo4j:5-community
    
  2. Populate a sample hierarchy with an intentional cycle:
    CREATE (a:OrgUnit {id: 'eng', name: 'Engineering'}),
           (b:OrgUnit {id: 'dev', name: 'Development'}),
           (c:OrgUnit {id: 'qa', name: 'QA'})
    CREATE (a)-[:INHERITS]->(b),
           (b)-[:INHERITS]->(c),
           (c)-[:INHERITS]->(a);
    
  3. Configure the required secrets in your Kestra namespace:
    • NEO4J_USERNAME: neo4j
    • NEO4J_PASSWORD: testpassword123
    • SLACK_WEBHOOK_URL: https://hooks.slack.com/services/...
  4. Execute the flow in dry_run: "true" mode to verify cycle detection without mutating edges.
  5. Review the execution outputs and inspect the generated JSON audit certificate in Kestra internal storage.
  6. Run with dry_run: "false" and auto_sever_cycle: "true" to confirm that the closing edge is severed and the hierarchy is restored to a valid DAG.

How to extend

  • Quarantine Edge Relabeling: Instead of directly deleting the closing edge, alter the Cypher remediation step to delete [:INHERITS] and recreate it as a [:QUARANTINED_CYCLE_EDGE] with an incident_id property for manual human triage.
  • Webhook Event Trigger: Add a io.kestra.plugin.core.trigger.Webhook trigger to automatically invoke this integrity gate immediately after upstream dbt or Kafka batch sync jobs finish.
  • Jira Incident Escalation: Integrate io.kestra.plugin.jira.issues.Create to automatically open a bug ticket assigned to the data steward owning the affected entity.
  • Multi-Tenant Hierarchy Iteration: Wrap the cycle query inside a io.kestra.plugin.core.flow.Loop loop across all distinct business units or tenant graph partitions.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.