Inferensys

Prompt

Migration Ordering Dependency Check Prompt

A practical prompt playbook for using the Migration Ordering Dependency Check Prompt in production AI workflows to validate migration sequence correctness across services.
Cinematic shot of a sleek glass-walled boardroom on the 40th floor of a glass highrise, late afternoon light casting long shadows across a minimalist table with holographic AI workflow projections.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the job-to-be-done, ideal user, required context, and boundaries for the Migration Ordering Dependency Check Prompt.

This prompt is designed for release engineers and platform teams who need to validate the execution order of database migration scripts across multiple services before a deployment. It ingests a migration manifest that lists every migration file, its target service, and its declared dependencies, then produces a dependency graph analysis. The output identifies circular dependencies, missing prerequisites, and execution order violations that would cause deployment failures or data corruption if the migrations ran in the wrong sequence.

Use this prompt when you have a structured manifest of planned migrations and need an automated pre-flight check before any migration tool executes the scripts. The manifest must be accurate and complete; garbage in, garbage out applies. The prompt assumes each entry includes a unique migration identifier, the service it targets, and an explicit list of migration IDs it depends on. It does not introspect live databases, parse SQL, or validate the content of migration files. It only reasons about the declared dependency relationships.

Do not use this prompt for runtime schema introspection, for generating migration scripts from scratch, or for reviewing the SQL content inside individual migration files. It is not a replacement for integration testing or dry-run execution. If your manifest is incomplete or contains incorrect dependency declarations, the analysis will be wrong. For high-risk deployments, always pair this automated check with a human review of the dependency graph and a dry-run against a production-like environment before proceeding.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Migration Ordering Dependency Check Prompt delivers value and where it creates risk. Use these cards to decide if this prompt fits your release workflow before wiring it into a deployment pipeline.

01

Good Fit: Multi-Service Release Orchestration

Use when: you have 5+ migration scripts spanning independent services or databases that must execute in a specific order. Why: manual dependency tracing across service boundaries is error-prone and slow. The prompt excels at cross-referencing foreign key references, view dependencies, and ETL pipeline requirements to flag ordering violations before they reach production.

02

Bad Fit: Single-Schema, Linear Migrations

Avoid when: all migrations live in one schema with a single linear execution path and no cross-service dependencies. Why: the prompt adds latency and token cost without surfacing insights a simple topological sort wouldn't catch. A deterministic build tool or ORM migration runner handles this case more reliably.

03

Required Input: Complete Migration Manifest

What to watch: the prompt cannot reason about dependencies it cannot see. Guardrail: require a structured manifest containing every migration file path, target schema, explicit depends_on declarations, and any DDL statements that reference objects outside the migration's owning schema. Incomplete manifests produce false-negative dependency reports.

04

Operational Risk: Stale Dependency Assumptions

What to watch: the prompt analyzes the manifest you provide, not the live database state. If schema metadata has drifted since the manifest was generated, dependency analysis will be wrong. Guardrail: regenerate the manifest from actual schema introspection output immediately before running the prompt. Never reuse a manifest from a prior release cycle.

05

Operational Risk: Circular Dependency False Negatives

What to watch: circular dependencies that span three or more migrations can be missed if the prompt analyzes pairwise relationships without full transitive closure. Guardrail: always pair the prompt output with a deterministic cycle-detection step in your harness. Use the prompt for explanation and risk context, not as the sole cycle-detection mechanism.

06

Not a Replacement: Execution Order Enforcement

What to watch: the prompt produces a dependency graph and risk report, not an execution plan. Teams sometimes treat the output as the migration run order without validating it against their orchestrator's actual sequencing. Guardrail: feed the prompt's dependency graph into your migration runner as a validation check, not as the source of truth for execution order. The orchestrator still owns sequencing.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A ready-to-use prompt that analyzes a migration manifest to detect circular dependencies, missing prerequisites, and execution order violations.

The following prompt template is designed to be pasted directly into your AI workflow. It expects a structured migration manifest as input and produces a dependency graph analysis. The placeholders in square brackets must be replaced with your actual data and constraints before execution. This template is self-contained and can be used independently of the surrounding playbook, but you should always review its output against your known service architecture and deployment topology.

text
You are a release engineering assistant specializing in database migration dependency analysis.

Your task is to analyze the provided migration manifest and produce a dependency graph report that identifies circular dependencies, missing prerequisites, and execution order violations.

## INPUT
[MIGRATION_MANIFEST]

## CONSTRAINTS
- Assume each migration entry includes at minimum: service name, migration ID, declared dependencies (list of migration IDs it requires), and target schema version.
- Treat the declared dependency list as the source of truth for intended ordering.
- Flag any migration that references a dependency not present in the manifest.
- Detect all cycles in the dependency graph, regardless of cycle length.
- Identify any migration that appears in the manifest but is not reachable from any entry point (orphaned migration).
- Do not invent dependencies. Only use what is declared in the manifest.

## OUTPUT_SCHEMA
Return a valid JSON object with the following structure:
{
  "dependency_graph": {
    "nodes": [
      {
        "migration_id": "string",
        "service": "string",
        "declared_dependencies": ["string"],
        "all_transitive_dependencies": ["string"]
      }
    ],
    "edges": [
      {
        "from": "string (dependency)",
        "to": "string (dependent migration)"
      }
    ]
  },
  "findings": {
    "circular_dependencies": [
      {
        "cycle": ["string"],
        "severity": "BLOCKER",
        "description": "string explaining the cycle"
      }
    ],
    "missing_prerequisites": [
      {
        "migration_id": "string",
        "missing_dependency": "string",
        "severity": "BLOCKER",
        "description": "string"
      }
    ],
    "execution_order_violations": [
      {
        "violation_type": "REQUIRES_REORDER | ORPHANED | DUPLICATE_ID",
        "migration_ids": ["string"],
        "severity": "BLOCKER | WARNING",
        "description": "string"
      }
    ],
    "valid_execution_order": ["string"]
  },
  "summary": {
    "total_migrations": 0,
    "blocker_count": 0,
    "warning_count": 0,
    "is_executable": false
  }
}

## RULES
1. The `valid_execution_order` must be a topologically sorted list of all migration IDs that respects all non-circular dependencies. If cycles exist, this field must be an empty array.
2. `is_executable` must be `true` only if there are zero BLOCKER findings.
3. For each circular dependency, include the full cycle path in the `cycle` array.
4. For missing prerequisites, the `missing_dependency` is the ID that is referenced but not present in the manifest.
5. Classify orphaned migrations (no other migration depends on them and they depend on nothing) as `execution_order_violations` with type `ORPHANED` and severity `WARNING`.
6. Classify duplicate migration IDs as `execution_order_violations` with type `DUPLICATE_ID` and severity `BLOCKER`.

## RISK_LEVEL
HIGH — Incorrect migration ordering can cause data corruption, service outages, and difficult rollbacks. Always validate this output against your deployment pipeline's actual execution plan before applying migrations.

To adapt this template, replace [MIGRATION_MANIFEST] with your actual migration data. The manifest should be a structured list, ideally JSON or YAML, containing at minimum the fields described in the CONSTRAINTS section. If your manifest uses different field names, update the prompt's assumptions accordingly. For high-risk production environments, always pair this prompt's output with a human review step and a dry-run execution in a staging environment before approving any migration sequence.

IMPLEMENTATION TABLE

Prompt Variables

Placeholders required by the Migration Ordering Dependency Check Prompt. Wire these into your harness before invoking the model.

PlaceholderPurposeExampleValidation Notes

[MIGRATION_MANIFEST]

Ordered list of migration scripts, versions, and target schemas

v2.1.0: add_users_email_idx.sql -> users v2.1.1: alter_orders_fk.sql -> orders

Must be parseable as a sequence. Validate that each entry includes a version identifier, a script name, and a target schema. Reject if ordering is ambiguous.

[SCHEMA_DEFINITIONS]

Current DDL for all schemas referenced in the manifest

CREATE TABLE users (id UUID PRIMARY KEY, email TEXT); CREATE TABLE orders (user_id UUID REFERENCES users(id));

Must be valid SQL DDL. Parse with a SQL parser before injection. If DDL is missing for a schema referenced in the manifest, flag as incomplete input.

[DEPENDENCY_RULES]

Explicit dependency constraints between migrations

v2.1.1 REQUIRES v2.1.0 v2.2.0 MUST RUN AFTER v2.1.1

Optional. If provided, each rule must reference valid migration versions from the manifest. Reject rules referencing unknown versions.

[SERVICE_OWNERSHIP_MAP]

Mapping of schemas or tables to owning services

users -> user-service orders -> order-service

Optional. If provided, validate that every schema in the manifest has an owner. Used to flag cross-service ordering violations.

[EXECUTION_CONTEXT]

Target environment and execution constraints

ENVIRONMENT: production PARALLELISM: sequential DRY_RUN: false

Required. Must specify environment. If DRY_RUN is true, the prompt should note that analysis is hypothetical and no locks are held.

[KNOWN_ISSUES]

Previously identified dependency problems or exceptions

v2.1.0 and v2.1.1 can run in parallel v2.2.0 has a known 30s lock window

Optional. If provided, each issue must reference valid migration versions. Used to suppress false positives in the dependency graph.

[OUTPUT_SCHEMA]

Expected structure for the dependency graph analysis

{"cycles": [...], "missing_prerequisites": [...], "order_violations": [...], "safe_parallel_groups": [...]}

Required. Must be a valid JSON Schema or example object. The harness should validate the model output against this schema and retry on mismatch.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Migration Ordering Dependency Check Prompt into a CI/CD pipeline with validation, retries, and human review gates.

The Migration Ordering Dependency Check Prompt is designed to operate as a pre-deployment gate in a release pipeline, not as an ad-hoc chat interaction. The prompt expects a structured migration manifest—typically a JSON or YAML document listing migration files, their declared dependencies, target databases, and execution order metadata—as its primary input. The harness should extract this manifest from the repository's migration directory, version control metadata, or an orchestration tool's plan file before constructing the prompt. Because the output is a dependency graph analysis with specific violation types (circular dependencies, missing prerequisites, execution order violations), the harness must validate that the model's response conforms to the expected schema before allowing the pipeline to proceed.

Wire the prompt into a CI/CD workflow by adding a dedicated stage after migration artifact assembly but before any deployment approval step. The harness should: (1) assemble the migration manifest from the source of truth (e.g., parsing Flyway, Alembic, or Liquibase metadata files); (2) inject the manifest into the [MIGRATION_MANIFEST] placeholder along with any [KNOWN_CONSTRAINTS] such as service startup order or shared database dependencies; (3) call the model with a low temperature setting (0.0–0.2) to maximize deterministic graph analysis; (4) parse the JSON output and validate it against a schema that requires dependency_graph, violations[], cycle_details[], and recommended_order[] fields; (5) if validation fails, retry once with the validation error appended as additional context; (6) if the retry also fails, fail the pipeline stage and surface the raw output for human review. For high-risk migrations involving financial data, PII, or irreversible DDL, add a mandatory human approval gate that presents the dependency graph visualization and violation summary before the migration can execute.

Model choice matters here: use a model with strong structured reasoning capabilities and reliable JSON output. GPT-4o, Claude 3.5 Sonnet, and Gemini 1.5 Pro all perform well on dependency graph analysis when given explicit schema constraints. Avoid smaller or older models that may conflate dependency types or hallucinate non-existent cycles. Log every invocation—including the manifest hash, model response, validation result, and reviewer decision—to create an audit trail for post-migration incident analysis. The most common production failure mode is a manifest that contains implicit dependencies not declared in migration metadata (e.g., an application code assumption about table existence). Mitigate this by enriching the manifest with schema introspection data before prompt construction, and by treating the prompt's missing_prerequisites output as a signal to update migration metadata, not just a gate failure.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, format, and validation rules for the migration ordering dependency check response. Use this contract to parse, validate, and integrate the model output into your release pipeline.

Field or ElementType or FormatRequiredValidation Rule

dependency_graph

JSON object with nodes and edges arrays

Must parse as valid JSON. Nodes array must contain unique migration IDs matching [MIGRATION_MANIFEST] entries. Edges must reference only existing node IDs.

dependency_graph.nodes[].id

string matching manifest migration identifier

Must match a migration ID present in the input [MIGRATION_MANIFEST]. No orphaned or invented IDs allowed.

dependency_graph.edges[].from

string matching a node id

Must reference an existing node in dependency_graph.nodes. Source node must appear before target node in execution order.

circular_dependencies

array of arrays of strings

Each inner array must contain 2+ migration IDs forming a cycle. IDs must exist in nodes. Empty array if no cycles detected. Schema check: array of string arrays.

missing_prerequisites

array of objects with dependent_id and missing_id

Each object must have both keys. dependent_id and missing_id must reference valid migration IDs from [MIGRATION_MANIFEST]. Empty array if all prerequisites present.

execution_order_violations

array of objects with earlier_id and later_id

Each object must have both keys. earlier_id must appear after later_id in the proposed order. IDs must exist in manifest. Empty array if order is valid.

proposed_execution_order

array of strings in dependency-respecting sequence

Must contain every migration ID from [MIGRATION_MANIFEST] exactly once. Order must satisfy all edges in dependency_graph. No duplicates, no omissions.

assessment_summary

string with severity classification

Must be one of: SAFE_TO_EXECUTE, WARNING_DEPENDENCIES_UNSATISFIED, BLOCKED_CIRCULAR_DEPENDENCY, INCOMPLETE_ORDER. Must match findings in other fields. No free-text severity outside these values.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when using a migration ordering dependency check prompt and how to guard against it.

01

Incomplete Dependency Graph

What to watch: The model identifies explicit foreign key dependencies but misses implicit dependencies from triggers, stored procedures, application-level joins, or ETL pipelines that aren't declared in the schema. This produces a dependency graph that looks correct but omits critical execution order constraints. Guardrail: Feed the prompt a pre-computed dependency manifest from schema introspection tools (pg_depend, information_schema, ORM migration state) rather than relying on the model to infer all edges from raw SQL alone.

02

Circular Dependency False Negatives

What to watch: The model fails to detect circular dependencies when the cycle spans more than two migrations or crosses service boundaries. A migration that appears independent in isolation may create a deadlock when sequenced with migrations from other teams. Guardrail: Run a graph cycle detection algorithm (Tarjan's or Johnson's) on the extracted dependency edges before accepting the prompt output. Use the prompt for explanation and remediation suggestions, not as the sole cycle detector.

03

Version Drift Between Manifest and Reality

What to watch: The migration manifest provided as input is stale—it reflects last week's schema state, not the current state after hotfixes, manual patches, or out-of-band changes. The prompt produces a valid ordering for a schema that no longer exists. Guardrail: Require a timestamped schema snapshot or migration history query as a mandatory input field. Add a pre-check that compares the manifest timestamp against the last known applied migration before running the dependency analysis.

04

Ordering That Ignores Lock Contention

What to watch: The prompt produces a logically correct migration order that is operationally dangerous—it sequences long-running ALTER TABLE operations on high-traffic tables without considering lock acquisition order, causing cascading application timeouts during deployment. Guardrail: Add a [TABLE_SIZE_AND_ACCESS_PATTERNS] input section with row counts, access frequency, and expected lock duration. Instruct the prompt to flag any ordering that places heavy-lock migrations before light-lock migrations on shared resources.

05

Cross-Service Ordering Assumptions

What to watch: The prompt assumes all migrations run in a single atomic sequence, but in microservice environments, Team A's migration must complete before Team B's deployment can begin. The prompt output lacks service-boundary annotations and deployment-phase grouping. Guardrail: Include a [SERVICE_OWNERSHIP_MAP] input that tags each migration with its owning service. Instruct the prompt to produce a phased ordering grouped by service boundary, with explicit inter-service sequencing gates.

06

Rollback Order Reversal Errors

What to watch: The prompt correctly orders forward migrations but either omits rollback ordering or assumes rollback is a simple reverse of the forward sequence. In practice, rollback order must account for data written after migration, partial failures, and irreversible operations. Guardrail: Explicitly request a separate rollback ordering section in the output schema. Add a validation rule that checks whether any irreversible migration appears in the forward sequence and, if so, requires a rollback strategy annotation rather than a simple reverse step.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the Migration Ordering Dependency Check Prompt before production deployment. Each row defines a pass standard, a failure signal, and a concrete test method.

CriterionPass StandardFailure SignalTest Method

Circular Dependency Detection

Output identifies all cycles with participating nodes listed in order

Cycle count is zero when known cycles exist in [MIGRATION_MANIFEST]

Inject manifest with A->B, B->C, C->A; verify cycle reported with all three nodes

Missing Prerequisite Flagging

Every migration with an unsatisfied dependency is flagged with the specific missing prerequisite name

Migration passes validation despite referencing a non-existent prerequisite ID

Remove one migration from manifest; confirm dependent migration is flagged with missing prerequisite reference

Execution Order Validity

Proposed order respects all declared dependencies; no migration appears before its prerequisites

A migration appears in the sequence before a migration it depends on

Verify for every dependency pair (A depends on B) that B's position < A's position in output order

Orphan Node Handling

Migrations with no dependencies and no dependents are included in the order without errors

Orphan migrations are omitted from output or incorrectly flagged as errors

Include a standalone migration with zero dependency edges; confirm it appears in final order

Multi-Service Dependency Resolution

Cross-service dependencies are tracked and ordered correctly across service boundaries

Dependencies between services are ignored or treated as within-service only

Create manifest with ServiceA.Migration1 depending on ServiceB.Migration2; verify cross-service ordering

Output Schema Compliance

Output matches [OUTPUT_SCHEMA] exactly: dependency_graph, execution_order, circular_dependencies, missing_prerequisites, warnings fields present

Required field missing, extra field present, or field type mismatch

Validate output against JSON Schema; all required fields present with correct types

Edge Case: Empty Manifest

Returns valid output with empty execution_order and no errors when [MIGRATION_MANIFEST] contains zero migrations

Throws error, returns null, or produces hallucinated migrations

Submit empty migration list; confirm clean empty response with all required fields

Edge Case: Self-Referencing Dependency

Self-referencing dependency is flagged in warnings without crashing analysis

Self-reference causes infinite loop, timeout, or unhandled exception

Include migration with dependency on its own ID; confirm warning present and analysis completes

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a single migration manifest. Use a lightweight JSON schema for the output but skip strict enum validation and retry logic. Focus on getting a readable dependency graph and a list of ordering violations. Accept free-text explanations for each violation.

code
Analyze the following migration manifest and identify dependency ordering issues.

[MIGRATION_MANIFEST]

Return a JSON object with:
- "dependency_graph": a node-edge structure
- "violations": an array of objects with "migration", "issue_type", and "explanation"
- "safe_execution_order": a proposed sequence

Watch for

  • The model inventing dependencies not present in the manifest
  • Circular dependency detection that misses indirect cycles (A→B→C→A)
  • Ordering suggestions that ignore transaction boundaries or schema namespaces
  • Output that drifts from the requested JSON structure when manifests are large
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.