Skip to content

Deferred Validation Feature (formerly Lazy Validation)

Overview

The deferred validation feature (previously called lazy validation) allows deferring all validation checks until synthesis time, providing better error reporting and potential performance benefits for certain use cases.

Usage

Enable via App Parameter

import tempfile

from nf.core import App, Resource, Stack
from nf.core.exceptions import ValidationError

app = App(nf_id="demo", deferred_validation=True)
stack = Stack(nf_scope=app, nf_id="my-stack")

# These won't fail immediately even with errors
Resource(nf_scope=stack, nf_id="bucket", nf_type="aws_s3_bucket")
Resource(nf_scope=stack, nf_id="bucket", nf_type="aws_s3_bucket")  # Duplicate!

# All validations run here
try:
    app.synth(outdir=tempfile.mkdtemp())
except ValidationError as e:
    print(f"Validation failed: {e}")

Enable with a Flag or pyproject.toml

nf --deferred-validation synth
[tool.nf.config]
deferred_validation = true

Either overrides the App argument. Nothing is read from the environment.

Validation Report File

For detailed error analysis, name a report file:

nf synth --deferred-validation --validation-report-file /tmp/validation_errors.json

Architecture

Components

  1. ValidationAccumulator - Collects deferred validations
  2. DeferredValidation - Represents a single validation check
  3. ValidationType - Enum for different validation types
  4. App.deferred_validation - Toggle to enable/disable the feature

How It Works

  1. When deferred_validation=True, validation checks are not executed immediately
  2. Instead, they are stored in the ValidationAccumulator
  3. During App.synth(), all accumulated validations are executed
  4. Errors are collected and reported comprehensively

Supported Validations

  • Duplicate construct IDs
  • Duplicate resource IDs
  • Circular stack dependencies
  • Self-referencing stack dependencies
  • Missing required fields

Performance Characteristics

Benefits

  1. Faster resource creation when errors are expected (32-48% faster)
  2. Comprehensive error reporting - see all errors at once
  3. Better developer experience - no need to fix errors one by one
  4. Works well on large graphs - especially during iterative development

Trade-offs

  1. Deferred error detection - errors only surface during synthesis
  2. Memory overhead - validations are stored until synthesis
  3. Slightly slower for clean cases - due to validation tracking overhead

Performance Results

Scenario Immediate Deferred Improvement
100 resources (no errors) 0.70ms 0.71ms -2%
1000 resources (no errors) 6.46ms 6.24ms 3.4%
1000 resources + 100 duplicates 11.11ms 7.93ms 28.6%

Best Practices

  1. Use for development - Great for iterative development with frequent errors
  2. Enable report file - For debugging complex validation failures
  3. Not for production - Immediate validation is better for CI/CD

Example: Complex Infrastructure

import tempfile
from pathlib import Path

from nf.core import App, Resource, Stack
from nf.core.config.flags import flags
from nf.core.exceptions import ValidationError

report = Path(tempfile.mkdtemp()) / "validation_errors.json"

# Enable deferred validation for development (as nf --deferred-validation would)
with flags(deferred_validation=True, validation_report_file=str(report)):
    app = App(nf_id="demo")
    stack1 = Stack(nf_scope=app, nf_id="web-tier")
    stack2 = Stack(nf_scope=app, nf_id="data-tier")

    # Create many resources
    for i in range(100):
        Resource(nf_scope=stack1, nf_id=f"server_{i}", nf_type="aws_instance")

    # Oops, duplicate!
    Resource(nf_scope=stack1, nf_id="server_50", nf_type="aws_instance")

    # Create circular dependency (won't fail immediately)
    stack1.add_dependency(stack2)
    stack2.add_dependency(stack1)

    # All errors reported here
    try:
        app.synth(outdir=tempfile.mkdtemp())
    except ValidationError:
        print(f"Check {report} for details")

Implementation Details

Validation Accumulator

The ValidationAccumulator class manages deferred validations:

from nf.core.exceptions import ValidationError
from nf.core.constructs.validation import (
    DeferredValidation,
    ValidationAccumulator,
    ValidationType,
)


def check_name() -> None:
    raise ValidationError("name is required")


accumulator = ValidationAccumulator()
accumulator.add_validation(
    DeferredValidation(
        construct_path="demo/my-stack/bucket",
        validation_type=ValidationType.MISSING_REQUIRED,
        check_fn=check_name,
        error_context={"field": "name"},
    )
)
# add_duplicate_check, add_circular_dependency_check and add_required_field_check
# queue the built-in checks the same way.

for error, validation in accumulator.run_all_validations():
    print(validation.construct_path, error)

Integration Points

  1. Construct._add_child - Defers duplicate ID checks
  2. Stack.add_dependency - Defers circular dependency checks
  3. Resource.init - Defers required field checks
  4. App.synth - Executes all deferred validations

Future Enhancements

  1. Parallel validation execution - Run validations in parallel for large apps
  2. Validation caching - Cache validation results between runs
  3. Progressive validation - Validate incrementally as constructs are added
  4. Custom validation hooks - Allow users to add their own deferred validations
  5. Smart batching threshold - Automatically enable for large construct counts