This prompt is designed for data engineers and MLOps teams who need to automate recovery from row-level constraint violations during ETL staging-area loads. The primary job-to-be-done is to take a single violating row, the exact constraint definition it failed, and any referenced context (such as a parent table lookup for a FOREIGN KEY violation) and return either a repaired row that satisfies the constraint or a structured rejection with a specific violation code. It is not a general data cleaning tool or a one-shot fix for an entire batch of bad data. Its value is realized inside a retry loop within a data pipeline harness, where the model acts as a specialized repair function for individual records that block ingestion.
Prompt
Constraint Violation Self-Correction Prompt

When to Use This Prompt
Defines the ideal job-to-be-done, required context, and operational boundaries for the constraint violation self-correction prompt.
To use this prompt effectively, the calling harness must provide three concrete inputs: the raw violating row, the DDL or constraint definition that was violated, and the specific error message from the database or validation engine. For FOREIGN KEY violations, the harness must also execute a lookup against the referenced table and supply the set of valid key values as context before invoking the model. The prompt assumes the upstream error is available and unambiguous. It is not designed to diagnose silent data corruption, infer missing constraints, or handle violations that span multiple rows simultaneously. The output must be validated by the harness before the repaired row is re-attempted against the target table.
Do not use this prompt when the violation rate is high enough to suggest a systemic upstream issue, such as a broken source system or a misconfigured schema mapping. In those cases, root-cause analysis and pipeline repair are required before row-level retries. Do not use this prompt for constraints that carry regulatory or financial materiality without adding a human review step after the model's repair suggestion. The prompt is a tactical recovery tool for staging-area loads, not a replacement for data contracts, schema enforcement, or upstream data quality checks. After reading this section, proceed to the prompt template to see the exact instruction structure, then review the implementation harness to understand how to wire it into a retry loop with validation, logging, and escalation thresholds.
Use Case Fit
Where the Constraint Violation Self-Correction Prompt works, where it fails, and the operational conditions required for safe deployment in a staging-area recovery pipeline.
Good Fit: Deterministic Constraint Violations
Use when: A row fails a NOT NULL, UNIQUE, CHECK, or FOREIGN KEY constraint with a clear, machine-readable violation message. The prompt excels at mapping a specific error to a specific field and proposing a single-row correction. Guardrail: Always provide the exact constraint DDL and the violating row as structured input, not prose.
Bad Fit: Multi-Row Causal Failures
Avoid when: A FOREIGN KEY violation is caused by a missing parent row that must be loaded first, or when a UNIQUE violation requires merging multiple rows. The prompt operates on a single row and cannot reorder a batch. Guardrail: Use a pre-processing step to topologically sort batches by dependency before invoking this prompt for individual row repair.
Required Inputs: Constraint Definition and Referenced Context
Risk: Without the exact constraint DDL and the current state of referenced tables, the model will guess at valid values, potentially introducing new integrity errors. Guardrail: The prompt harness must query the target table for existing unique values and the referenced table for valid foreign keys, injecting both into the prompt context alongside the violation error.
Operational Risk: Silent Data Corruption
Risk: The model may 'repair' a value by truncating it to fit a CHECK constraint, losing information without logging the change. A NOT NULL violation might be filled with a plausible but incorrect default. Guardrail: The harness must log every repair decision with a before/after diff and require a human approval step if the repair rate exceeds a configurable threshold (e.g., 5% of a batch).
Operational Risk: Retry Loop Exhaustion
Risk: A repaired row might violate a different constraint, triggering a second repair attempt and an infinite loop. Guardrail: Implement a retry budget (e.g., 3 attempts per row). After the budget is exhausted, quarantine the row with a structured rejection code and escalate to a dead-letter queue for manual triage.
When to Escalate Instead of Repair
Avoid using this prompt when: The violation indicates a systemic upstream bug (e.g., a source system sending malformed data for an entire column) rather than a sporadic data quality issue. Repairing every row individually will mask the root cause. Guardrail: Monitor violation frequency by constraint type. If a single constraint fails for more than a configurable percentage of rows, halt the repair pipeline and alert the upstream data owner.
Copy-Ready Prompt Template
A copy-ready prompt for repairing a data row that violates a database constraint during ETL staging.
This prompt template is designed to be pasted directly into your AI harness. It instructs the model to act as a data repair specialist, taking a single violating row, the constraint it broke, and any relevant context (such as referenced table samples or lookup values). The model must return either a corrected row that satisfies the constraint or a structured rejection with a specific violation code. All dynamic values are represented as square-bracket placeholders—replace these with live data from your pipeline before each call.
textYou are a data repair specialist for an ETL staging area. Your task is to fix a single data row that has violated a database constraint during a load operation. ## INPUT - Violating Row (as JSON): [VIOLATING_ROW] - Constraint Definition: [CONSTRAINT_DEFINITION] - Constraint Type: [CONSTRAINT_TYPE] // e.g., NOT NULL, UNIQUE, CHECK, FOREIGN KEY - Referenced Context (if applicable): [REFERENCED_CONTEXT] // e.g., sample of existing rows for UNIQUE, lookup table for FOREIGN KEY - Target Table Schema: [TARGET_TABLE_SCHEMA] ## INSTRUCTIONS 1. Analyze the violating row against the constraint definition and referenced context. 2. Determine if a valid repair is possible without guessing critical business values. 3. If a repair is possible, produce a corrected row that satisfies the constraint. 4. If a repair is not possible, produce a structured rejection. ## OUTPUT SCHEMA Return ONLY a valid JSON object with this exact structure: { "status": "repaired" | "rejected", "repaired_row": { ... } | null, // The full corrected row as a JSON object if status is "repaired" "violation_code": "STRING", // A stable code from the list below "repair_description": "STRING", // A concise explanation of what was changed or why it was rejected "repair_confidence": 0.0-1.0 // Your confidence in the repair, where 1.0 is certain } ## VIOLATION CODES Use one of these exact codes: - `REPAIRED_NOT_NULL_FILLED`: Filled a NULL with a sensible default. - `REPAIRED_UNIQUE_DEDUPED`: Resolved a duplicate by adjusting a value. - `REPAIRED_CHECK_CORRECTED`: Corrected a value to satisfy a CHECK constraint. - `REPAIRED_FK_MAPPED`: Mapped a value to a valid foreign key reference. - `REJECTED_UNRECOVERABLE`: The row cannot be repaired without guessing critical business data. - `REJECTED_AMBIGUOUS`: Multiple valid repair options exist and the correct one is unclear. - `REJECTED_CONTEXT_MISSING`: Required referenced context was not provided. ## CONSTRAINTS - Do not invent business-critical values like customer IDs, monetary amounts, or dates that are not derivable from the provided context. - For NOT NULL violations on foreign key columns, prefer rejection over generating a placeholder value. - For UNIQUE violations, prefer adjusting the non-key attributes if a clear pattern exists; otherwise reject. - Preserve all other fields in the row exactly as provided unless they must change to satisfy the constraint. - If the constraint definition references a lookup table, use only values present in the referenced context.
To adapt this template, replace each [PLACEHOLDER] with live data from your pipeline. The [VIOLATING_ROW] should be a JSON object representing the entire row that failed validation. The [CONSTRAINT_DEFINITION] should contain the exact constraint rule as defined in your database or data quality framework. For FOREIGN KEY violations, populate [REFERENCED_CONTEXT] with a sample of valid keys from the referenced table—this grounds the model's repair decision in real data and prevents hallucinated references. After running the prompt, validate the output JSON against the schema before passing the repaired row to your loader. Log all rejections for manual review and track the repair_confidence field to build a quality baseline over time.
Prompt Variables
Inputs the constraint violation self-correction prompt needs to work reliably. Validate each before calling the model to prevent garbage-in-garbage-out repair attempts.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[VIOLATING_ROW] | The single data record that failed a constraint check during loading | {"customer_id": null, "order_total": -50.00, "region": "EU"} | Must be a valid JSON object or CSV row string. Check that the row is parseable and contains the column that triggered the violation. Null allowed only if the violation is a NOT NULL constraint on a nullable column. |
[CONSTRAINT_DEFINITION] | The exact constraint rule that was violated, including type and condition | NOT NULL constraint on column 'customer_id' in table 'orders' | Must include constraint type (NOT NULL, UNIQUE, CHECK, FOREIGN KEY) and the target column or expression. Parse to confirm the constraint type is recognized. Reject if constraint definition is empty or ambiguous. |
[REFERENCED_CONTEXT] | Supporting data needed to resolve the violation, such as lookup tables or valid value sets | Valid region codes: ['NA', 'EU', 'APAC', 'LATAM'] | Required for FOREIGN KEY and CHECK violations. For UNIQUE violations, provide the conflicting existing row. Validate that the context is parseable and matches the constraint type. Null allowed for NOT NULL violations with no external reference. |
[TABLE_SCHEMA] | The full column definitions and types for the target table | orders: customer_id INT NOT NULL, order_total DECIMAL(10,2) CHECK (order_total >= 0), region VARCHAR(10) NOT NULL | Must include column names, data types, and inline constraints. Parse to extract column list and types. Use to validate that the repaired row has correct column count and compatible types before returning. |
[REPAIR_POLICY] | Instructions for how aggressive the repair should be and when to reject instead of repair | Prefer imputation from context over null fill. Reject if FOREIGN KEY parent row is missing. | Must be a non-empty string with clear guidance on repair vs. rejection boundaries. Validate that the policy does not contradict the constraint definition. Default to 'repair when possible, reject with violation code when impossible' if not specified. |
[MAX_REPAIR_ATTEMPTS] | The retry budget counter for this specific row before escalation | 3 | Must be a positive integer. Validate that the value is numeric and greater than zero. If the counter exceeds this value, the harness should skip the prompt and escalate to dead-letter queue. Track per-row attempt count in the harness, not in the prompt. |
[OUTPUT_SCHEMA] | The expected structure for the prompt response, including repaired row and metadata | {"action": "repair" | "reject", "repaired_row": {...}, "violation_code": "...", "repair_reason": "..."} | Must define action enum, repaired_row shape, and required metadata fields. Validate that the schema is a valid JSON Schema or type definition. The harness must parse the response against this schema and retry on parse failure. |
Implementation Harness Notes
How to wire the Constraint Violation Self-Correction Prompt into a staging-area recovery pipeline with validation, retries, and audit logging.
The Constraint Violation Self-Correction Prompt is designed to sit inside a staging-area recovery loop, not as a standalone chatbot. When a batch load into a staging table fails with a constraint violation (NOT NULL, UNIQUE, CHECK, FOREIGN KEY), the pipeline should extract the offending row, the constraint definition from the database catalog, and any referenced context (e.g., the parent row for a FOREIGN KEY violation). This triplet—violating row, constraint, and context—becomes the input to the prompt. The model returns either a repaired row that satisfies the constraint or a structured rejection with a violation code. The harness must never automatically commit the repaired row to the target table without validation.
Wire the prompt into an ETL framework (Airflow, Prefect, Dagster, or a custom Python worker) as a recovery task triggered by a constraint error exception. The task should: (1) catch the database error and parse the constraint name and violation type from the exception message or the database's error metadata (e.g., PostgreSQL's PGresult.error_field); (2) query the information schema (information_schema.table_constraints, information_schema.check_constraints, information_schema.key_column_usage) to retrieve the full constraint definition; (3) for FOREIGN KEY violations, query the referenced table to retrieve the parent row that the violating row should reference; (4) assemble the prompt with the violating row serialized as a JSON object, the constraint definition as a SQL DDL fragment, and the referenced context as a JSON object; (5) call the model with a low temperature (0.0–0.2) to maximize deterministic repair behavior; (6) validate the model's output against a strict JSON schema that requires either a repaired_row object or a rejection object with a violation_code and reason; (7) if the output is a repaired row, re-run the constraint check against the staging table schema before inserting; (8) log every repair decision—original row, constraint, model output, validation result, and final disposition—to an audit table for traceability.
Retry logic must include a budget. Set a maximum of 2 retries for the same row. If the model's repair fails validation on the first attempt, feed the validation error back into the prompt as additional context and retry once. If the second attempt also fails, quarantine the row to a dead-letter table and escalate to a human operator via the notification channel your pipeline already uses (Slack, PagerDuty, email). Never loop indefinitely. For UNIQUE constraint violations where the model proposes a value that still collides, the harness should detect the collision on re-validation and treat it as a retryable failure. For CHECK constraints involving business logic (e.g., start_date < end_date), the harness should log the original expression and the model's interpretation to help operators audit whether the repair preserved the intent. Model choice matters: use a model with strong SQL and data reasoning capabilities (GPT-4o, Claude 3.5 Sonnet, or equivalent). Avoid lightweight models for this task because constraint repair requires understanding schema semantics, not just pattern matching.
Expected Output Contract
Defines the exact fields, types, and validation rules for the model response when a constraint violation is detected. Use this contract to build a parser that can reliably consume the output before staging the repaired row.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
violation_diagnosis | object | Must contain constraint_type, constraint_name, and offending_value sub-fields. constraint_type must be one of NOT_NULL, UNIQUE, CHECK, FOREIGN_KEY, or UNKNOWN. | |
repair_decision | string | Must be exactly REPAIRED, REJECTED, or ESCALATED. No other values allowed. | |
repaired_row | object or null | If repair_decision is REPAIRED, must be a valid JSON object with the same keys as the input row schema. If REJECTED or ESCALATED, must be null. | |
rejection_code | string or null | If repair_decision is REJECTED, must be a non-empty string from the allowed rejection code list. If REPAIRED, must be null. | |
repair_justification | string | Must be a non-empty string explaining the change made or the reason for rejection. Must reference the specific constraint violated. | |
confidence_score | number | Must be a float between 0.0 and 1.0 inclusive. Scores below 0.7 should trigger a human review flag in the harness. | |
escalation_reason | string or null | If repair_decision is ESCALATED, must be a non-empty string explaining why automatic repair was not possible. Otherwise must be null. |
Common Failure Modes
Constraint violation prompts fail in predictable ways. Here's what breaks first and how to guard against it.
Silent Data Corruption on Repair
What to watch: The model 'repairs' a violating row by silently changing a value to satisfy the constraint, but the new value is semantically wrong (e.g., changing a foreign key to a valid but incorrect ID). Guardrail: Always diff the repaired row against the original and log every changed field. Require a human-in-the-loop review for any repair that alters a foreign key or a monetary amount.
Constraint Misinterpretation
What to watch: The model misunderstands a complex CHECK constraint or a multi-column UNIQUE constraint and produces a repair that still violates the rule. Guardrail: Run the repaired row through the same database constraint validation before accepting it. If the repair fails validation again, increment a retry counter and escalate after two failed repair attempts.
Context Starvation for Foreign Keys
What to watch: A FOREIGN KEY violation occurs, but the referenced context provided to the prompt is incomplete or missing the valid parent row. The model hallucinates a plausible but incorrect parent key. Guardrail: Always include the full set of valid parent keys in the prompt context. If the referenced context is too large, pre-filter it with an exact lookup before calling the repair prompt.
Over-Eager Rejection
What to watch: The model rejects a row that could have been repaired with a simple, deterministic fix (e.g., trimming whitespace for a NOT NULL VARCHAR field). Guardrail: Implement a pre-processing layer for trivial, deterministic fixes before invoking the LLM. Reserve the self-correction prompt for genuinely ambiguous or multi-field violations only.
Repair Loop Exhaustion
What to watch: A single bad row triggers multiple repair-retry cycles because each 'fix' introduces a new constraint violation, creating an infinite loop. Guardrail: Enforce a hard retry budget (e.g., 3 attempts). After the budget is exhausted, quarantine the row with a REPAIR_EXHAUSTED violation code and log the full repair history for manual triage.
Implicit Type Coercion Drift
What to watch: The model changes a value's type to satisfy a constraint (e.g., converting a string to an integer), but the coercion logic is lossy or inconsistent with how the downstream application interprets the field. Guardrail: Validate that the repaired row's data types exactly match the target schema. Reject any repair that changes a column's primitive type without an explicit, logged justification.
Evaluation Rubric
Use this rubric to test the Constraint Violation Self-Correction Prompt before deploying it to a staging-area recovery pipeline. Each criterion targets a specific failure mode observed in row-repair workflows. Run these checks against a golden set of known constraint violations and verify the output programmatically.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
NOT NULL Repair | Repaired row supplies a valid, domain-appropriate value for the NOT NULL column; no empty string or placeholder unless domain-valid. | Output leaves the column null, inserts 'N/A' for a numeric field, or uses a generic placeholder like 'TBD'. | Parse the output row and assert the target column is non-null and passes a domain-specific regex or range check. |
UNIQUE Conflict Resolution | Repaired row contains a value that does not collide with any existing value in the provided [REFERENCED_CONTEXT]; or correctly rejects with violation code 'UNIQUE_CONFLICT'. | Output proposes a value that already exists in the referenced context without a disambiguation strategy. | Extract the repaired value and check for membership in the set of existing values from the test fixture's [REFERENCED_CONTEXT]. |
CHECK Constraint Satisfaction | Repaired row satisfies the boolean expression in [CONSTRAINT_DEFINITION]; e.g., start_date < end_date or amount > 0. | Output violates the CHECK expression when evaluated; e.g., flips dates without correcting the logic. | Evaluate the [CONSTRAINT_DEFINITION] expression programmatically against the repaired row's fields. |
FOREIGN KEY Validity | Repaired row references a key that exists in [REFERENCED_CONTEXT] or rejects with violation code 'FK_ORPHAN'. | Output invents a foreign key value not present in the referenced context. | Look up the foreign key value in the provided [REFERENCED_CONTEXT] lookup table; assert existence or rejection. |
Rejection Code Format | When repair is impossible, output includes a structured rejection with a machine-readable 'violation_code' from the allowed set. | Rejection is free-text only, missing the violation_code field, or uses an undefined code. | Parse the output; if 'action' is 'reject', assert 'violation_code' is present and matches the enum [NOT_NULL_VIOLATION, UNIQUE_CONFLICT, CHECK_FAILED, FK_ORPHAN]. |
Semantic Preservation | Repaired row preserves all other valid fields unchanged; only the violating field is modified or imputed. | Output drops, reorders, or silently alters fields that were not in violation. | Diff the input [VIOLATING_ROW] against the output row; assert only the column named in [CONSTRAINT_DEFINITION] has changed. |
Null Imputation Reason | When a NOT NULL repair imputes a value, the output includes a non-empty 'imputation_reason' field. | Output imputes a value but omits the imputation_reason or leaves it null. | If the repaired field differs from the input and the input was null, assert 'imputation_reason' is a non-empty string. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Add schema validation, retry budget tracking, structured logging, and eval cases. Wrap the prompt in a harness that validates the output against the target table schema before accepting the repair.
codeYou are a data repair assistant operating inside a staging-area recovery pipeline. A row failed validation against the target schema. Constraint type: [CONSTRAINT_TYPE] Constraint definition: [CONSTRAINT_DEFINITION] Violating row (JSON): [VIOLATING_ROW] Referenced context: [REFERENCED_CONTEXT] Target table schema: [TARGET_SCHEMA] Retry attempt: [RETRY_ATTEMPT] of [MAX_RETRIES] Return a JSON object: { "action": "repair" | "reject" | "escalate", "repaired_row": { ... }, "violation_code": "NOT_NULL_VIOLATION" | "UNIQUE_VIOLATION" | "CHECK_VIOLATION" | "FK_VIOLATION" | "UNREPAIRABLE", "repair_reasoning": "string", "confidence": 0.0-1.0 } If confidence < 0.7, prefer "escalate" over "repair". Do not invent values not present in the referenced context.
Watch for
- Silent format drift—the model may change JSON key names over time
- Missing human review for high-impact tables (fact tables, financial data)
- Retry loops that burn budget without improving the repair

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us