Kailash DataFlow - Zero-Config Database Framework
DataFlow is a zero-config database framework built on Kailash Core SDK that automatically generates workflow nodes from database models.
Overview
DataFlow transforms database models into workflow nodes automatically, providing:
- Automatic Node Generation: 11 nodes per model (@db.model decorator)
- Multi-Database Support: PostgreSQL, MySQL, SQLite (SQL) + MongoDB (Document) + pgvector (Vector Search)
- Enterprise Features: Multi-tenancy, multi-instance isolation, transactions
- Zero Configuration: String IDs preserved, deferred schema operations
- Integration Ready: Works with Nexus for multi-channel deployment
- Specialized Adapters: SQL (11 nodes/model), Document (8 nodes), Vector (3 nodes)
L
🛠️ Developer Experience Tools
Enhanced Error System
DataFlow provides comprehensive error enhancement across all database operations, strict mode validation for build-time error prevention, and an intelligent debug agent for automated error diagnosis.
Error Enhancement
What It Is: Automatic transformation of Python exceptions into rich, actionable error messages with context, root causes, and solutions.
All DataFlow errors include:
- Error codes: DF-XXX format (DataFlow) or KS-XXX (Core SDK)
- Context: Node, parameters, workflow state
- Root causes: Why the error occurred (3-5 possibilities with probability scores)
- Solutions: How to fix it (with code examples)
Example:
# Missing parameter error shows:
# - Error Code: DF-101
# - Missing parameter: "id"
# - 3 solutions with code examples
# - Link to documentation
workflow.add_node("UserCreateNode", "create", {
"name": "Alice" # Missing "id" - error enhanced automatically
})
Error Categories:
- DF-1XX: Parameter errors (missing, type mismatch, validation)
- DF-2XX: Connection errors (missing, circular, type mismatch)
- DF-3XX: Migration errors (schema, constraints)
- DF-4XX: Configuration errors (database URL, auth)
- DF-5XX: Runtime errors (timeouts, resources)
Architecture:
# BaseErrorEnhancer - Shared abstraction
# ├─ CoreErrorEnhancer - KS-501 to KS-508 (Core SDK)
# └─ DataFlowErrorEnhancer - DF-XXX codes (DataFlow)
Strict Mode Validation
What It Is: Build-time validation system with 4 layers to catch errors before workflow execution.
Validation Layers:
- Model Validation - Primary keys, auto-fields, reserved fields, field types
- Parameter Validation - Required parameters, types, values, CreateNode structure
- Connection Validation - Source/target nodes, type compatibility, dot notation
- Workflow Validation - Structure, circular dependencies
Configuration:
from dataflow import DataFlow
from dataflow.validation.strict_mode import StrictModeConfig
config = StrictModeConfig(
enabled=True,
validate_models=True,
validate_parameters=True,
validate_connections=True,
validate_workflows=True,
fail_fast=True, # Stop on first error
verbose=False # Minimal output
)
db = DataFlow("postgresql://...", strict_mode_config=config)
When to Use:
- ✅ Development: Catch errors early
- ✅ CI/CD: Validate workflows before deployment
- ✅ Production: Prevent invalid workflow execution
Documentation:
- HOW-TO Guide:
dataflow-strict-mode
- Architecture Guide:
dataflow-validation-layers
Debug Agent
What It Is: Intelligent error analysis system that automatically diagnoses errors and provides ranked, actionable solutions.
5-Stage Pipeline:
- Capture - Stack traces, context, error chains
- Categorize - 50+ patterns across 5 categories (PARAMETER, CONNECTION, MIGRATION, RUNTIME, CONFIGURATION)
- Analyze - Inspector integration for workflow analysis
- Suggest - 60+ solution templates with relevance scoring
- Format - CLI (color-coded), JSON (machine-readable), dict (programmatic)
Usage:
from dataflow.debug.debug_agent import DebugAgent
from dataflow.debug.knowledge_base import KnowledgeBase
from dataflow.platform.inspector import Inspector
# Initialize once (singleton pattern)
kb = KnowledgeBase("patterns.yaml", "solutions.yaml")
inspector = Inspector(db)
debug_agent = DebugAgent(kb, inspector)
# Debug errors automatically
try:
runtime.execute(workflow.build())
except Exception as e:
report = debug_agent.debug(e, max_solutions=5, min_relevance=0.3)
print(report.to_cli_format()) # Rich terminal output
Output Formats:
# CLI format (color-coded, ANSI)
print(report.to_cli_format())
# JSON format (machine-readable)
json_output = report.to_json()
# Dictionary format (programmatic)
data = report.to_dict()
Performance: 5-50ms per error, 92%+ confidence for known patterns
Documentation:
- Skill Guide:
dataflow-debug-agent
- User Guide:
docs/guides/debug-agent-user-guide.md
- Developer Guide:
docs/guides/debug-agent-developer-guide.md
Build-Time Validation: Catch Errors Early
Validation Modes: OFF, WARN (default), STRICT
Catch 80% of configuration errors at model registration time (not runtime):
from dataflow import DataFlow
db = DataFlow("postgresql://...")
# Default: Warn mode (backward compatible)
@db.model
class User:
id: int # Validates: primary key named 'id'
name: str
email: str
# Strict mode: Raises errors on validation failures
@db.model(strict=True)
class Product:
id: int
name: str
price: float
# Skip validation (advanced users)
@db.model(skip_validation=True)
class Advanced:
custom_pk: int # Custom primary key allowed
Validation Checks:
- VAL-002: Missing primary key (error)
- VAL-003: Primary key not named 'id' (warning)
- VAL-004: Composite primary key (warning)
- VAL-005: Auto-managed field conflicts (created_at, updated_at)
- VAL-006: DateTime without timezone
- VAL-007: String/Text without length
- VAL-008: camelCase field names (should be snake_case)
- VAL-009: SQL reserved words as field names
- VAL-010: Missing delete cascade in relationships
When to Use Each Mode:
- OFF: Legacy code migration, custom implementations
- WARN (default): Development, catches issues without blocking
- STRICT: Production deployments, enforce standards
ErrorEnhancer: Actionable Error Messages
Automatic error enhancement with context, root causes, and solutions:
from dataflow import DataFlow
from dataflow.core.error_enhancer import ErrorEnhancer
db = DataFlow("postgresql://...")
# ErrorEnhancer automatically integrated into DataFlow engine
# Enhanced errors show:
# - Error code (DF-101, DF-102, etc.)
# - Context (node, parameters, workflow state)
# - Root causes with probability scores
# - Actionable solutions with code templates
# - Documentation links
try:
# Missing parameter error
workflow.add_node("UserCreateNode", "create", {})
except Exception as e:
# ErrorEnhancer automatically catches and enriches
# Shows: DF-101 with specific fixes
pass
Key Features:
- 40+ Error Codes: DF-101 (missing parameter) through DF-805 (runtime errors)
- Pattern Matching: Automatic error detection and classification
- Contextual Solutions: Code templates with variable substitution
- Color-Coded Output: Emojis and formatting for readability
- Documentation Links: Direct links to relevant guides
Common Errors Covered:
- DF-101: Missing required parameter
- DF-102: Type mismatch (expected dict, got str)
- DF-103: Auto-managed field conflict (created_at, updated_at)
- DF-104: Wrong node pattern (CreateNode vs UpdateNode)
- DF-105: Primary key 'id' missing/wrong name
- DF-201: Invalid connection - source output not found
- DF-301: Migration failed - table already exists
See: sdk-users/apps/dataflow/troubleshooting/top-10-errors.md
Inspector API: Self-Service Debugging
Introspection API for workflows, nodes, connections, and parameters:
from dataflow.platform.inspector import Inspector
inspector = Inspector(dataflow_instance)
inspector.workflow_obj = workflow.build()
# Connection Analysis
connections = inspector.connections() # List all connections
broken = inspector.find_broken_connections() # Find issues
validation = inspector.validate_connections() # Check validity
# Parameter Tracing
trace = inspector.trace_parameter("create_user", "data")
print(f"Source: {trace.source_node}")
dependencies = inspector.parameter_dependencies("create_user")
# Node Analysis
deps = inspector.node_dependencies("create_user") # Upstream
dependents = inspector.node_dependents("create_user") # Downstream
order = inspector.execution_order() # Topological sort
# Workflow Validation
report = inspector.workflow_validation_report()
if not report['is_valid']:
print(f"Errors: {report['errors']}")
print(f"Warnings: {report['warnings']}")
print(f"Suggestions: {report['suggestions']}")
# High-Level Overview
summary = inspector.workflow_summary()
metrics = inspector.workflow_metrics()
Inspector Methods (18 total):
- Connection Analysis (5): connections(), connection_chain(), connection_graph(), validate_connections(), find_broken_connections()
- Parameter Tracing (5): trace_parameter(), parameter_flow(), find_parameter_source(), parameter_dependencies(), parameter_consumers()
- Node Analysis (5): node_dependencies(), node_dependents(), execution_order(), node_schema(), compare_nodes()
- Workflow Analysis (3): workflow_summary(), workflow_metrics(), workflow_validation_report()
Use Cases:
- Diagnose "missing parameter" errors
- Find broken connections
- Trace parameter flow through workflows
- Validate workflows before execution
- Generate workflow documentation
- Debug complex workflows
Performance: <1ms per method call (cached operations)
CLI Tools: Industry-Standard Workflow Validation
Command-line tools matching pytest/mypy patterns for workflow validation and debugging:
# Validate workflow structure and connections
dataflow-validate workflow.py --output text
dataflow-validate workflow.py --fix # Auto-fix common issues
dataflow-validate workflow.py --output json > report.json
# Analyze workflow metrics and complexity
dataflow-analyze workflow.py --verbosity 2
dataflow-analyze workflow.py --format json
# Generate reports and documentation
dataflow-generate workflow.py report --output-dir ./reports
dataflow-generate workflow.py diagram # ASCII workflow diagram
dataflow-generate workflow.py docs --output-dir ./docs
# Debug workflows with breakpoints
dataflow-debug workflow.py --breakpoint create_user
dataflow-debug workflow.py --inspect-node create_user
dataflow-debug workflow.py --step # Step-by-step execution
# Profile performance and detect bottlenecks
dataflow-perf workflow.py --bottlenecks
dataflow-perf workflow.py --recommend
dataflow-perf workflow.py --format json > perf.json
CLI Commands (5 total):
- dataflow-validate: Validate workflow structure, connections, and parameters with --fix flag
- dataflow-analyze: Workflow metrics, complexity analysis, and execution order
- dataflow-generate: Generate reports, diagrams (ASCII), and documentation
- dataflow-debug: Interactive debugging with breakpoints and node inspection
- dataflow-perf: Performance profiling, bottleneck detection, and recommendations
Use Cases:
- CI/CD integration for workflow validation
- Pre-deployment validation checks
- Performance profiling and optimization
- Documentation generation
- Interactive debugging sessions
Performance: Industry-standard CLI tool performance (<100ms startup)
Common Pitfalls Guide
New: Comprehensive guides for common DataFlow mistakes
CreateNode vs UpdateNode (saves 1-2 hours):
- Side-by-side comparison
- Decision tree for node selection
- 10+ working examples
- Common mistakes and fixes
- See:
sdk-users/apps/dataflow/guides/create-vs-update.md
Top 10 Errors (saves 30-120 minutes per error):
- Quick fix guide for 90% of issues
- Error code reference (DF-101 through DF-805)
- Diagnosis decision tree
- Prevention checklist
- Inspector commands for debugging
- See:
sdk-users/apps/dataflow/troubleshooting/top-10-errors.md
Quick Start
from dataflow import DataFlow
from kailash.workflow.builder import WorkflowBuilder
from kailash.runtime.local import LocalRuntime
# Initialize DataFlow
db = DataFlow(connection_string="postgresql://user:pass@localhost/db")
# Define model (generates 11 nodes automatically)
@db.model
class User:
id: str # String IDs preserved
name: str
email: str
# Use generated nodes in workflows
workflow = WorkflowBuilder()
workflow.add_node("User_Create", "create_user", {
"data": {"name": "John", "email": "john@example.com"}
})
# Execute
runtime = LocalRuntime()
results, run_id = runtime.execute(workflow.build())
user_id = results["create_user"]["result"] # Access pattern
Reference Documentation
Getting Started
- dataflow-quickstart - Quick start guide and core concepts
- dataflow-installation - Installation and setup
- dataflow-models - Defining models with @db.model decorator
- dataflow-connection-config - Database connection configuration
Core Operations
- dataflow-crud-operations - Create, Read, Update, Delete operations
- dataflow-queries - Query patterns and filtering
- dataflow-bulk-operations - Batch operations for performance
- dataflow-transactions - Transaction management
- dataflow-connection-isolation - ⚠️ CRITICAL: Connection isolation and ACID guarantees
- dataflow-result-access - Accessing results from nodes
Advanced Features
- dataflow-multi-instance - Multiple database instances
- dataflow-multi-tenancy - Multi-tenant architectures
- dataflow-existing-database - Working with existing databases
- dataflow-migrations-quick - Database migrations
- dataflow-custom-nodes - Creating custom database nodes
- dataflow-performance - Performance optimization
Integration & Deployment
- dataflow-nexus-integration - Deploying with Nexus platform
- dataflow-deployment - Production deployment patterns
- dataflow-dialects - Supported database dialects
- dataflow-monitoring - Monitoring and observability
Testing & Quality
- dataflow-tdd-mode - Test-driven development with DataFlow
- dataflow-tdd-api - Testing API for DataFlow
- dataflow-tdd-best-practices - Testing best practices
- dataflow-compliance - Compliance and standards
Troubleshooting & Debugging
- create-vs-update guide - CreateNode vs UpdateNode comprehensive guide
- top-10-errors - Quick fix guide for 90% of issues
- dataflow-gotchas - Common pitfalls and solutions
- dataflow-strict-mode - Strict mode validation HOW-TO guide (Week 9)
- dataflow-validation-layers - 4-layer validation architecture (Week 9)
- dataflow-debug-agent - Intelligent error analysis with 5-stage pipeline (Week 10)
- ErrorEnhancer: Automatic error enhancement (integrated in DataFlow engine) - Enhanced in Week 7
- Inspector API: Self-service debugging (18 introspection methods)
- CLI Tools: Industry-standard command-line validation and debugging tools (5 commands)
Key Concepts
Not an ORM
DataFlow is NOT an ORM. It's a workflow framework that:
- Generates workflow nodes from models
- Operates within Kailash's workflow execution model
- Uses string-based result access patterns
- Integrates seamlessly with other workflow nodes
Automatic Node Generation
Each @db.model class generates 11 nodes:
{Model}_Create - Create single record
{Model}_Read - Read by ID
{Model}_Update - Update record
{Model}_Delete - Delete record
{Model}_List - List with filters
{Model}_Upsert - Insert or update (atomic)
{Model}_Count - Efficient COUNT(*) queries
{Model}_BulkCreate - Bulk insert
{Model}_BulkUpdate - Bulk update
{Model}_BulkDelete - Bulk delete
{Model}_BulkUpsert - Bulk upsert
Critical Rules
- ✅ String IDs preserved (no UUID conversion)
- ✅ Deferred schema operations (safe for Docker/FastAPI)
- ✅ Multi-instance isolation (one DataFlow per database)
- ✅ Result access:
results["node_id"]["result"]
- ❌ NEVER use truthiness checks on filter/data parameters (empty dict
{} is falsy)
- ❌ ALWAYS use key existence checks:
if "filter" in kwargs instead of if kwargs.get("filter")
- ❌ NEVER use direct SQL when DataFlow nodes exist
- ❌ NEVER use SQLAlchemy/Django ORM alongside DataFlow
Database Support
- SQL Databases: PostgreSQL, MySQL, SQLite (11 nodes per @db.model)
- Document Database: MongoDB with flexible schema (8 specialized nodes)
- Vector Search: PostgreSQL pgvector for RAG/AI (3 vector nodes)
- 100% Feature Parity: SQL databases support identical workflows
When to Use This Skill
Use DataFlow when you need to:
- Perform database operations in workflows
- Generate CRUD APIs automatically (with Nexus)
- Implement multi-tenant systems
- Work with existing databases
- Build database-first applications
- Handle bulk data operations
- Implement enterprise data management
Integration Patterns
With Nexus (Multi-Channel)
from dataflow import DataFlow
from nexus import Nexus
db = DataFlow(connection_string="...")
@db.model
class User:
id: str
name: str
# Auto-generates API + CLI + MCP
nexus = Nexus(db.get_workflows())
nexus.run() # Instant multi-channel platform
With Core SDK (Custom Workflows)
from dataflow import DataFlow
from kailash.workflow.builder import WorkflowBuilder
db = DataFlow(connection_string="...")
# Use db-generated nodes in custom workflows
workflow = WorkflowBuilder()
workflow.add_node("User_Create", "user1", {...})
Multi-Database Support Matrix
SQL Databases (DatabaseAdapter)
- PostgreSQL: Full support with advanced features (asyncpg driver, pgvector extension, native arrays)
- MySQL: Full support with 100% feature parity (aiomysql driver)
- SQLite: Full support for development/testing/mobile (aiosqlite + custom pooling)
- Nodes Generated: 11 per @db.model (Create, Read, Update, Delete, List, Upsert, Count, BulkCreate, BulkUpdate, BulkDelete, BulkUpsert)
Document Databases (MongoDBAdapter)
- MongoDB: Complete NoSQL support (Motor async driver)
- Features: Flexible schema, aggregation pipelines, text search, geospatial queries
- Workflow Nodes: 8 specialized nodes (DocumentInsert, DocumentFind, DocumentUpdate, DocumentDelete, BulkDocumentInsert, Aggregate, CreateIndex, DocumentCount)
- Use Cases: E-commerce catalogs, content management, user profiles, event logs
Vector Databases (PostgreSQLVectorAdapter)
- PostgreSQL pgvector: Semantic similarity search for RAG/AI (pgvector extension)
- Features: Cosine/L2/inner product distance, HNSW/IVFFlat indexes
- Workflow Nodes: 3 vector nodes (VectorSearch, VectorInsert, VectorUpdate)
- Use Cases: RAG applications, semantic search, recommendation engines
Architecture
- BaseAdapter: Minimal interface for all adapter types (adapter_type, database_type, health_check)
- DatabaseAdapter: SQL-specific (inherits BaseAdapter)
- MongoDBAdapter: Document database (inherits BaseAdapter)
- PostgreSQLVectorAdapter: Vector operations (inherits DatabaseAdapter)
Planned Extensions
- TimescaleDB: Time-series data optimization (PostgreSQL extension)
- Qdrant/Milvus: Dedicated vector databases with advanced filtering
- Redis: Caching and key-value operations
- Neo4j: Graph database with Cypher queries
Related Skills
Support
For DataFlow-specific questions, invoke:
dataflow-specialist - DataFlow implementation and patterns
testing-specialist - DataFlow testing strategies (NO MOCKING policy)
framework-advisor - Choose between Core SDK and DataFlow
1---2name: dataflow3description: Kailash DataFlow - zero-config database framework with automatic model-to-node generation. Use when asking about 'database operations', 'DataFlow', 'database models', 'CRUD operations', 'bulk operations', 'database queries', 'database migrations', 'multi-tenancy', 'multi-instance', 'database transactions', 'PostgreSQL', 'MySQL', 'SQLite', 'MongoDB', 'pgvector', 'vector search', 'document database', 'RAG', 'semantic search', 'existing database', 'database performance', 'database deployment', 'database testing', or 'TDD with databases'. DataFlow is NOT an ORM - it generates 11 workflow nodes per SQL model, 8 nodes for MongoDB, and 3 nodes for vector operations.4---5
6# Kailash DataFlow - Zero-Config Database Framework
7
8DataFlow is a zero-config database framework built on Kailash Core SDK that automatically generates workflow nodes from database models.
9
10## Overview
11
12DataFlow transforms database models into workflow nodes automatically, providing:
13
14- **Automatic Node Generation**: 11 nodes per model (@db.model decorator)
15- **Multi-Database Support**: PostgreSQL, MySQL, SQLite (SQL) + MongoDB (Document) + pgvector (Vector Search)
16- **Enterprise Features**: Multi-tenancy, multi-instance isolation, transactions
17- **Zero Configuration**: String IDs preserved, deferred schema operations
18- **Integration Ready**: Works with Nexus for multi-channel deployment
19- **Specialized Adapters**: SQL (11 nodes/model), Document (8 nodes), Vector (3 nodes)
20L
21## 🛠️ Developer Experience Tools
22
23### Enhanced Error System
24
25DataFlow provides comprehensive error enhancement across all database operations, strict mode validation for build-time error prevention, and an intelligent debug agent for automated error diagnosis.
26
27#### Error Enhancement
28
29**What It Is**: Automatic transformation of Python exceptions into rich, actionable error messages with context, root causes, and solutions.
30
31**All DataFlow errors include**:
32- **Error codes**: DF-XXX format (DataFlow) or KS-XXX (Core SDK)
33- **Context**: Node, parameters, workflow state
34- **Root causes**: Why the error occurred (3-5 possibilities with probability scores)
35- **Solutions**: How to fix it (with code examples)
36
37**Example**:
38```python
39# Missing parameter error shows:
40# - Error Code: DF-101
41# - Missing parameter: "id"
42# - 3 solutions with code examples
43# - Link to documentation
44
45workflow.add_node("UserCreateNode", "create", {
46 "name": "Alice" # Missing "id" - error enhanced automatically
47})
48```
49
50**Error Categories**:
51- **DF-1XX**: Parameter errors (missing, type mismatch, validation)
52- **DF-2XX**: Connection errors (missing, circular, type mismatch)
53- **DF-3XX**: Migration errors (schema, constraints)
54- **DF-4XX**: Configuration errors (database URL, auth)
55- **DF-5XX**: Runtime errors (timeouts, resources)
56
57**Architecture**:
58```python
59# BaseErrorEnhancer - Shared abstraction
60# ├─ CoreErrorEnhancer - KS-501 to KS-508 (Core SDK)
61# └─ DataFlowErrorEnhancer - DF-XXX codes (DataFlow)
62```
63
64#### Strict Mode Validation
65
66**What It Is**: Build-time validation system with 4 layers to catch errors before workflow execution.
67
68**Validation Layers**:
691. **Model Validation** - Primary keys, auto-fields, reserved fields, field types
702. **Parameter Validation** - Required parameters, types, values, CreateNode structure
713. **Connection Validation** - Source/target nodes, type compatibility, dot notation
724. **Workflow Validation** - Structure, circular dependencies
73
74**Configuration**:
75```python
76from dataflow import DataFlow
77from dataflow.validation.strict_mode import StrictModeConfig
78
79config = StrictModeConfig(
80 enabled=True,
81 validate_models=True,
82 validate_parameters=True,
83 validate_connections=True,
84 validate_workflows=True,
85 fail_fast=True, # Stop on first error
86 verbose=False # Minimal output
87)
88
89db = DataFlow("postgresql://...", strict_mode_config=config)
90```
91
92**When to Use**:
93- ✅ Development: Catch errors early
94- ✅ CI/CD: Validate workflows before deployment
95- ✅ Production: Prevent invalid workflow execution
96
97**Documentation**:
98- HOW-TO Guide: [`dataflow-strict-mode`](dataflow-strict-mode.md)
99- Architecture Guide: [`dataflow-validation-layers`](dataflow-validation-layers.md)
100
101#### Debug Agent
102
103**What It Is**: Intelligent error analysis system that automatically diagnoses errors and provides ranked, actionable solutions.
104
105**5-Stage Pipeline**:
1061. **Capture** - Stack traces, context, error chains
1072. **Categorize** - 50+ patterns across 5 categories (PARAMETER, CONNECTION, MIGRATION, RUNTIME, CONFIGURATION)
1083. **Analyze** - Inspector integration for workflow analysis
1094. **Suggest** - 60+ solution templates with relevance scoring
1105. **Format** - CLI (color-coded), JSON (machine-readable), dict (programmatic)
111
112**Usage**:
113```python
114from dataflow.debug.debug_agent import DebugAgent
115from dataflow.debug.knowledge_base import KnowledgeBase
116from dataflow.platform.inspector import Inspector
117
118# Initialize once (singleton pattern)
119kb = KnowledgeBase("patterns.yaml", "solutions.yaml")
120inspector = Inspector(db)
121debug_agent = DebugAgent(kb, inspector)
122
123# Debug errors automatically
124try:
125 runtime.execute(workflow.build())
126except Exception as e:
127 report = debug_agent.debug(e, max_solutions=5, min_relevance=0.3)
128 print(report.to_cli_format()) # Rich terminal output
129```
130
131**Output Formats**:
132```python
133# CLI format (color-coded, ANSI)
134print(report.to_cli_format())
135
136# JSON format (machine-readable)
137json_output = report.to_json()
138
139# Dictionary format (programmatic)
140data = report.to_dict()
141```
142
143**Performance**: 5-50ms per error, 92%+ confidence for known patterns
144
145**Documentation**:
146- Skill Guide: [`dataflow-debug-agent`](dataflow-debug-agent.md)
147- User Guide: `docs/guides/debug-agent-user-guide.md`
148- Developer Guide: `docs/guides/debug-agent-developer-guide.md`
149
150---
151
152### Build-Time Validation: Catch Errors Early
153**Validation Modes**: OFF, WARN (default), STRICT
154
155Catch 80% of configuration errors at model registration time (not runtime):
156
157```python
158from dataflow import DataFlow
159
160db = DataFlow("postgresql://...")
161
162# Default: Warn mode (backward compatible)
163@db.model
164class User:
165 id: int # Validates: primary key named 'id'
166 name: str
167 email: str
168
169# Strict mode: Raises errors on validation failures
170@db.model(strict=True)
171class Product:
172 id: int
173 name: str
174 price: float
175
176# Skip validation (advanced users)
177@db.model(skip_validation=True)
178class Advanced:
179 custom_pk: int # Custom primary key allowed
180```
181
182**Validation Checks**:
183- **VAL-002**: Missing primary key (error)
184- **VAL-003**: Primary key not named 'id' (warning)
185- **VAL-004**: Composite primary key (warning)
186- **VAL-005**: Auto-managed field conflicts (created_at, updated_at)
187- **VAL-006**: DateTime without timezone
188- **VAL-007**: String/Text without length
189- **VAL-008**: camelCase field names (should be snake_case)
190- **VAL-009**: SQL reserved words as field names
191- **VAL-010**: Missing delete cascade in relationships
192
193**When to Use Each Mode**:
194- **OFF**: Legacy code migration, custom implementations
195- **WARN** (default): Development, catches issues without blocking
196- **STRICT**: Production deployments, enforce standards
197
198---
199
200### ErrorEnhancer: Actionable Error Messages
201
202Automatic error enhancement with context, root causes, and solutions:
203
204```python
205from dataflow import DataFlow
206from dataflow.core.error_enhancer import ErrorEnhancer
207
208db = DataFlow("postgresql://...")
209
210# ErrorEnhancer automatically integrated into DataFlow engine
211# Enhanced errors show:
212# - Error code (DF-101, DF-102, etc.)
213# - Context (node, parameters, workflow state)
214# - Root causes with probability scores
215# - Actionable solutions with code templates
216# - Documentation links
217
218try:
219 # Missing parameter error
220 workflow.add_node("UserCreateNode", "create", {})
221except Exception as e:
222 # ErrorEnhancer automatically catches and enriches
223 # Shows: DF-101 with specific fixes
224 pass
225```
226
227**Key Features**:
228- **40+ Error Codes**: DF-101 (missing parameter) through DF-805 (runtime errors)
229- **Pattern Matching**: Automatic error detection and classification
230- **Contextual Solutions**: Code templates with variable substitution
231- **Color-Coded Output**: Emojis and formatting for readability
232- **Documentation Links**: Direct links to relevant guides
233
234**Common Errors Covered**:
235- DF-101: Missing required parameter
236- DF-102: Type mismatch (expected dict, got str)
237- DF-103: Auto-managed field conflict (created_at, updated_at)
238- DF-104: Wrong node pattern (CreateNode vs UpdateNode)
239- DF-105: Primary key 'id' missing/wrong name
240- DF-201: Invalid connection - source output not found
241- DF-301: Migration failed - table already exists
242
243**See**: `sdk-users/apps/dataflow/troubleshooting/top-10-errors.md`
244
245---
246
247### Inspector API: Self-Service Debugging
248
249Introspection API for workflows, nodes, connections, and parameters:
250
251```python
252from dataflow.platform.inspector import Inspector
253
254inspector = Inspector(dataflow_instance)
255inspector.workflow_obj = workflow.build()
256
257# Connection Analysis
258connections = inspector.connections() # List all connections
259broken = inspector.find_broken_connections() # Find issues
260validation = inspector.validate_connections() # Check validity
261
262# Parameter Tracing
263trace = inspector.trace_parameter("create_user", "data")
264print(f"Source: {trace.source_node}")
265dependencies = inspector.parameter_dependencies("create_user")
266
267# Node Analysis
268deps = inspector.node_dependencies("create_user") # Upstream
269dependents = inspector.node_dependents("create_user") # Downstream
270order = inspector.execution_order() # Topological sort
271
272# Workflow Validation
273report = inspector.workflow_validation_report()
274if not report['is_valid']:
275 print(f"Errors: {report['errors']}")
276 print(f"Warnings: {report['warnings']}")
277 print(f"Suggestions: {report['suggestions']}")
278
279# High-Level Overview
280summary = inspector.workflow_summary()
281metrics = inspector.workflow_metrics()
282```
283
284**Inspector Methods** (18 total):
285- **Connection Analysis** (5): connections(), connection_chain(), connection_graph(), validate_connections(), find_broken_connections()
286- **Parameter Tracing** (5): trace_parameter(), parameter_flow(), find_parameter_source(), parameter_dependencies(), parameter_consumers()
287- **Node Analysis** (5): node_dependencies(), node_dependents(), execution_order(), node_schema(), compare_nodes()
288- **Workflow Analysis** (3): workflow_summary(), workflow_metrics(), workflow_validation_report()
289
290**Use Cases**:
291- Diagnose "missing parameter" errors
292- Find broken connections
293- Trace parameter flow through workflows
294- Validate workflows before execution
295- Generate workflow documentation
296- Debug complex workflows
297
298**Performance**: <1ms per method call (cached operations)
299
300---
301
302### CLI Tools: Industry-Standard Workflow Validation
303
304Command-line tools matching pytest/mypy patterns for workflow validation and debugging:
305
306```bash
307# Validate workflow structure and connections
308dataflow-validate workflow.py --output text
309dataflow-validate workflow.py --fix # Auto-fix common issues
310dataflow-validate workflow.py --output json > report.json
311
312# Analyze workflow metrics and complexity
313dataflow-analyze workflow.py --verbosity 2
314dataflow-analyze workflow.py --format json
315
316# Generate reports and documentation
317dataflow-generate workflow.py report --output-dir ./reports
318dataflow-generate workflow.py diagram # ASCII workflow diagram
319dataflow-generate workflow.py docs --output-dir ./docs
320
321# Debug workflows with breakpoints
322dataflow-debug workflow.py --breakpoint create_user
323dataflow-debug workflow.py --inspect-node create_user
324dataflow-debug workflow.py --step # Step-by-step execution
325
326# Profile performance and detect bottlenecks
327dataflow-perf workflow.py --bottlenecks
328dataflow-perf workflow.py --recommend
329dataflow-perf workflow.py --format json > perf.json
330```
331
332**CLI Commands** (5 total):
333- **dataflow-validate**: Validate workflow structure, connections, and parameters with --fix flag
334- **dataflow-analyze**: Workflow metrics, complexity analysis, and execution order
335- **dataflow-generate**: Generate reports, diagrams (ASCII), and documentation
336- **dataflow-debug**: Interactive debugging with breakpoints and node inspection
337- **dataflow-perf**: Performance profiling, bottleneck detection, and recommendations
338
339**Use Cases**:
340- CI/CD integration for workflow validation
341- Pre-deployment validation checks
342- Performance profiling and optimization
343- Documentation generation
344- Interactive debugging sessions
345
346**Performance**: Industry-standard CLI tool performance (<100ms startup)
347
348---
349
350### Common Pitfalls Guide
351**New**: Comprehensive guides for common DataFlow mistakes
352
353**CreateNode vs UpdateNode** (saves 1-2 hours):
354- Side-by-side comparison
355- Decision tree for node selection
356- 10+ working examples
357- Common mistakes and fixes
358- **See**: `sdk-users/apps/dataflow/guides/create-vs-update.md`
359
360**Top 10 Errors** (saves 30-120 minutes per error):
361- Quick fix guide for 90% of issues
362- Error code reference (DF-101 through DF-805)
363- Diagnosis decision tree
364- Prevention checklist
365- Inspector commands for debugging
366- **See**: `sdk-users/apps/dataflow/troubleshooting/top-10-errors.md`
367
368---
369
370## Quick Start
371
372```python
373from dataflow import DataFlow
374from kailash.workflow.builder import WorkflowBuilder
375from kailash.runtime.local import LocalRuntime
376
377# Initialize DataFlow
378db = DataFlow(connection_string="postgresql://user:pass@localhost/db")
379
380# Define model (generates 11 nodes automatically)
381@db.model
382class User:
383 id: str # String IDs preserved
384 name: str
385 email: str
386
387# Use generated nodes in workflows
388workflow = WorkflowBuilder()
389workflow.add_node("User_Create", "create_user", {
390 "data": {"name": "John", "email": "john@example.com"}
391})
392
393# Execute
394runtime = LocalRuntime()
395results, run_id = runtime.execute(workflow.build())
396user_id = results["create_user"]["result"] # Access pattern
397```
398
399## Reference Documentation
400
401### Getting Started
402- **[dataflow-quickstart](dataflow-quickstart.md)** - Quick start guide and core concepts
403- **[dataflow-installation](dataflow-installation.md)** - Installation and setup
404- **[dataflow-models](dataflow-models.md)** - Defining models with @db.model decorator
405- **[dataflow-connection-config](dataflow-connection-config.md)** - Database connection configuration
406
407### Core Operations
408- **[dataflow-crud-operations](dataflow-crud-operations.md)** - Create, Read, Update, Delete operations
409- **[dataflow-queries](dataflow-queries.md)** - Query patterns and filtering
410- **[dataflow-bulk-operations](dataflow-bulk-operations.md)** - Batch operations for performance
411- **[dataflow-transactions](dataflow-transactions.md)** - Transaction management
412- **[dataflow-connection-isolation](dataflow-connection-isolation.md)** - ⚠️ CRITICAL: Connection isolation and ACID guarantees
413- **[dataflow-result-access](dataflow-result-access.md)** - Accessing results from nodes
414
415### Advanced Features
416- **[dataflow-multi-instance](dataflow-multi-instance.md)** - Multiple database instances
417- **[dataflow-multi-tenancy](dataflow-multi-tenancy.md)** - Multi-tenant architectures
418- **[dataflow-existing-database](dataflow-existing-database.md)** - Working with existing databases
419- **[dataflow-migrations-quick](dataflow-migrations-quick.md)** - Database migrations
420- **[dataflow-custom-nodes](dataflow-custom-nodes.md)** - Creating custom database nodes
421- **[dataflow-performance](dataflow-performance.md)** - Performance optimization
422
423### Integration & Deployment
424- **[dataflow-nexus-integration](dataflow-nexus-integration.md)** - Deploying with Nexus platform
425- **[dataflow-deployment](dataflow-deployment.md)** - Production deployment patterns
426- **[dataflow-dialects](dataflow-dialects.md)** - Supported database dialects
427- **[dataflow-monitoring](dataflow-monitoring.md)** - Monitoring and observability
428
429### Testing & Quality
430- **[dataflow-tdd-mode](dataflow-tdd-mode.md)** - Test-driven development with DataFlow
431- **[dataflow-tdd-api](dataflow-tdd-api.md)** - Testing API for DataFlow
432- **[dataflow-tdd-best-practices](dataflow-tdd-best-practices.md)** - Testing best practices
433- **[dataflow-compliance](dataflow-compliance.md)** - Compliance and standards
434
435### Troubleshooting & Debugging
436- **[create-vs-update guide](../../../sdk-users/apps/dataflow/guides/create-vs-update.md)** - CreateNode vs UpdateNode comprehensive guide
437- **[top-10-errors](../../../sdk-users/apps/dataflow/troubleshooting/top-10-errors.md)** - Quick fix guide for 90% of issues
438- **[dataflow-gotchas](dataflow-gotchas.md)** - Common pitfalls and solutions
439- **[dataflow-strict-mode](dataflow-strict-mode.md)** - Strict mode validation HOW-TO guide (Week 9)
440- **[dataflow-validation-layers](dataflow-validation-layers.md)** - 4-layer validation architecture (Week 9)
441- **[dataflow-debug-agent](dataflow-debug-agent.md)** - Intelligent error analysis with 5-stage pipeline (Week 10)
442- **ErrorEnhancer**: Automatic error enhancement (integrated in DataFlow engine) - Enhanced in Week 7
443- **Inspector API**: Self-service debugging (18 introspection methods)
444- **CLI Tools**: Industry-standard command-line validation and debugging tools (5 commands)
445
446## Key Concepts
447
448### Not an ORM
449DataFlow is **NOT an ORM**. It's a workflow framework that:
450- Generates workflow nodes from models
451- Operates within Kailash's workflow execution model
452- Uses string-based result access patterns
453- Integrates seamlessly with other workflow nodes
454
455### Automatic Node Generation
456Each `@db.model` class generates **11 nodes**:
4571. `{Model}_Create` - Create single record
4582. `{Model}_Read` - Read by ID
4593. `{Model}_Update` - Update record
4604. `{Model}_Delete` - Delete record
4615. `{Model}_List` - List with filters
4626. `{Model}_Upsert` - Insert or update (atomic)
4637. `{Model}_Count` - Efficient COUNT(*) queries
4648. `{Model}_BulkCreate` - Bulk insert
4659. `{Model}_BulkUpdate` - Bulk update
46610. `{Model}_BulkDelete` - Bulk delete
46711. `{Model}_BulkUpsert` - Bulk upsert
468
469### Critical Rules
470- ✅ String IDs preserved (no UUID conversion)
471- ✅ Deferred schema operations (safe for Docker/FastAPI)
472- ✅ Multi-instance isolation (one DataFlow per database)
473- ✅ Result access: `results["node_id"]["result"]`
474- ❌ NEVER use truthiness checks on filter/data parameters (empty dict `{}` is falsy)
475- ❌ ALWAYS use key existence checks: `if "filter" in kwargs` instead of `if kwargs.get("filter")`
476- ❌ NEVER use direct SQL when DataFlow nodes exist
477- ❌ NEVER use SQLAlchemy/Django ORM alongside DataFlow
478
479### Database Support
480- **SQL Databases**: PostgreSQL, MySQL, SQLite (11 nodes per @db.model)
481- **Document Database**: MongoDB with flexible schema (8 specialized nodes)
482- **Vector Search**: PostgreSQL pgvector for RAG/AI (3 vector nodes)
483- **100% Feature Parity**: SQL databases support identical workflows
484
485## When to Use This Skill
486
487Use DataFlow when you need to:
488- Perform database operations in workflows
489- Generate CRUD APIs automatically (with Nexus)
490- Implement multi-tenant systems
491- Work with existing databases
492- Build database-first applications
493- Handle bulk data operations
494- Implement enterprise data management
495
496## Integration Patterns
497
498### With Nexus (Multi-Channel)
499```python
500from dataflow import DataFlow
501from nexus import Nexus
502
503db = DataFlow(connection_string="...")
504@db.model
505class User:
506 id: str
507 name: str
508
509# Auto-generates API + CLI + MCP
510nexus = Nexus(db.get_workflows())
511nexus.run() # Instant multi-channel platform
512```
513
514### With Core SDK (Custom Workflows)
515```python
516from dataflow import DataFlow
517from kailash.workflow.builder import WorkflowBuilder
518
519db = DataFlow(connection_string="...")
520# Use db-generated nodes in custom workflows
521workflow = WorkflowBuilder()
522workflow.add_node("User_Create", "user1", {...})
523```
524
525## Multi-Database Support Matrix
526
527### SQL Databases (DatabaseAdapter)
528- **PostgreSQL**: Full support with advanced features (asyncpg driver, pgvector extension, native arrays)
529- **MySQL**: Full support with 100% feature parity (aiomysql driver)
530- **SQLite**: Full support for development/testing/mobile (aiosqlite + custom pooling)
531- **Nodes Generated**: 11 per @db.model (Create, Read, Update, Delete, List, Upsert, Count, BulkCreate, BulkUpdate, BulkDelete, BulkUpsert)
532
533### Document Databases (MongoDBAdapter)
534- **MongoDB**: Complete NoSQL support (Motor async driver)
535- **Features**: Flexible schema, aggregation pipelines, text search, geospatial queries
536- **Workflow Nodes**: 8 specialized nodes (DocumentInsert, DocumentFind, DocumentUpdate, DocumentDelete, BulkDocumentInsert, Aggregate, CreateIndex, DocumentCount)
537- **Use Cases**: E-commerce catalogs, content management, user profiles, event logs
538
539### Vector Databases (PostgreSQLVectorAdapter)
540- **PostgreSQL pgvector**: Semantic similarity search for RAG/AI (pgvector extension)
541- **Features**: Cosine/L2/inner product distance, HNSW/IVFFlat indexes
542- **Workflow Nodes**: 3 vector nodes (VectorSearch, VectorInsert, VectorUpdate)
543- **Use Cases**: RAG applications, semantic search, recommendation engines
544
545### Architecture
546- **BaseAdapter**: Minimal interface for all adapter types (adapter_type, database_type, health_check)
547- **DatabaseAdapter**: SQL-specific (inherits BaseAdapter)
548- **MongoDBAdapter**: Document database (inherits BaseAdapter)
549- **PostgreSQLVectorAdapter**: Vector operations (inherits DatabaseAdapter)
550
551### Planned Extensions
552- **TimescaleDB**: Time-series data optimization (PostgreSQL extension)
553- **Qdrant/Milvus**: Dedicated vector databases with advanced filtering
554- **Redis**: Caching and key-value operations
555- **Neo4j**: Graph database with Cypher queries
556
557## Related Skills
558
559- **[01-core-sdk](../../01-core-sdk/SKILL.md)** - Core workflow patterns
560- **[03-nexus](../nexus/SKILL.md)** - Multi-channel deployment
561- **[04-kaizen](../kaizen/SKILL.md)** - AI agent integration
562- **[17-gold-standards](../../17-gold-standards/SKILL.md)** - Best practices
563
564## Support
565
566For DataFlow-specific questions, invoke:
567- `dataflow-specialist` - DataFlow implementation and patterns
568- `testing-specialist` - DataFlow testing strategies (NO MOCKING policy)
569- `framework-advisor` - Choose between Core SDK and DataFlow