Inferensys

Prompt

Avro Schema Evolution Repair Prompt

A practical prompt playbook for using Avro Schema Evolution Repair Prompt in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for the Avro Schema Evolution Repair Prompt.

This prompt is for data platform teams and stream-processing engineers who encounter Avro schema compatibility failures at the point of consumption. The job-to-be-done is straightforward: a producer has written records using a writer schema that conflicts with the consumer's reader schema, and you need a programmatic resolution that preserves as much data as possible without manual record-by-record patching. The ideal user is an engineer integrating this prompt into an automated dead-letter queue (DLQ) recovery pipeline or a schema-registry remediation workflow. Required context includes the full writer schema, the full reader schema, and a sample of the failing records that triggered the compatibility error.

Do not use this prompt when the schema conflict is intentional and the correct behavior is to reject the records outright, or when the data loss risk is unacceptable for the domain (e.g., financial transactions where a default fill could misstate a value). This prompt is also inappropriate when the root cause is a producer bug that should be fixed upstream rather than patched at the consumer. The prompt assumes you have already ruled out simple solutions like updating the consumer to a newer schema version or adjusting the compatibility mode in your schema registry. It is a recovery tool for production incidents, not a substitute for schema design governance.

The prompt works best when you have a clear compatibility resolution policy defined before invocation: decide whether you prefer default fills, projection (dropping fields), or union widening for type mismatches. If your organization requires human approval for data modifications, wire this prompt into a review queue rather than an automated repair loop. The output should be treated as a candidate repair that requires validation against the reader schema and a semantic-diff check to confirm no critical fields were silently dropped or corrupted. For high-risk pipelines, always log the original failing record, the repair decision, and the corrected record for auditability.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Avro Schema Evolution Repair Prompt works and where it does not. Use these cards to decide if this prompt fits your pipeline before wiring it into production.

01

Good Fit: Schema Compatibility Resolution

Use when: a producer writes records with a schema that conflicts with the consumer's reader schema, and you need a compatibility resolution (default fill, projection, or union widening). Guardrail: always validate the repaired records against the reader schema before ingestion.

02

Bad Fit: Semantic Drift Without Schema Change

Avoid when: the schema is compatible but the meaning of fields has changed (e.g., a field now holds meters instead of feet). Guardrail: schema compatibility checks alone cannot detect semantic drift; pair with data quality rules that validate value ranges and distributions.

03

Required Input: Writer Schema, Reader Schema, and Failing Records

What to watch: the prompt needs the exact writer schema, reader schema, and a sample of failing records. Missing any of these leads to guesswork. Guardrail: extract schemas from your schema registry (not from memory) and include raw error messages from the deserialization failure.

04

Operational Risk: Data Loss from Aggressive Projection

Risk: the prompt may drop fields present in the writer schema but absent from the reader schema without logging the loss. Guardrail: require the output to include a dropped_fields array and log every dropped field to an audit table before the repaired records enter downstream systems.

05

Operational Risk: Default Fill Masking Real Errors

Risk: default fills for missing required fields can hide upstream producer bugs. Guardrail: attach a fill_reason to every defaulted field and set a threshold alert when the default-fill rate exceeds 5% of records in a batch.

06

Not a Replacement for Schema Registry Governance

Avoid when: you need to enforce organizational schema evolution policies (e.g., FORWARD, BACKWARD, FULL compatibility). Guardrail: this prompt repairs records after a compatibility break; it does not replace schema registry checks. Run compatibility tests in CI before producers deploy.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for diagnosing and repairing Avro schema evolution conflicts, producing a compatibility resolution and corrected records.

This template is the core instruction set for an AI model to act as a schema evolution repair engine. It is designed to be copied directly into your prompt management system, IDE, or orchestration harness. The prompt takes three critical inputs—the writer schema, the reader schema, and a sample of failing records—and forces the model to reason about the compatibility break before proposing a fix. Use square-bracket placeholders to inject your specific schemas, records, and operational constraints at runtime. The template is structured to separate the diagnostic reasoning from the repair action, making the output auditable.

code
You are an Avro schema evolution repair specialist. Your task is to diagnose a compatibility conflict between a writer schema and a reader schema, then repair a batch of failing records so they can be successfully deserialized by the consumer.

## INPUT

[WRITER_SCHEMA]
[READER_SCHEMA]
[FAILING_RECORDS]

## CONSTRAINTS

- [CONSTRAINTS]

## INSTRUCTIONS

1.  **Diagnose the Conflict:** Compare the writer and reader schemas. Identify every field that causes a schema resolution error (type mismatch, missing default, namespace conflict, etc.). Explain the root cause of the incompatibility.
2.  **Propose a Resolution Strategy:** For each conflicting field, choose exactly one resolution action from the list below. Justify your choice based on Avro schema evolution rules and the provided constraints.
    - `default_fill`: Apply a sensible default value for a new field in the reader schema that is missing in the writer records.
    - `projection`: Drop a field from the writer records that is not present in the reader schema.
    - `union_widening`: Wrap a field's value in a union type to match a widened reader schema (e.g., `int` to `["int", "long"]`).
    - `type_coercion`: Perform a safe type conversion (e.g., `int` to `string`) if the constraints allow it.
    - `reject`: Mark the record as irreparable if no safe resolution exists.
3.  **Repair the Records:** Apply your resolution strategy to each record in the [FAILING_RECORDS] list. Produce a corrected version of each record that conforms to the [READER_SCHEMA].
4.  **Flag Unresolvable Issues:** If any record cannot be fully repaired, flag it with a `repair_status` of `"partial"` or `"failed"` and provide a clear reason.

## OUTPUT_SCHEMA

Your response must be a single, valid JSON object conforming to this structure:

{
  "diagnosis": {
    "incompatibility_type": "string",
    "conflicting_fields": [
      {
        "field_name": "string",
        "writer_type": "string",
        "reader_type": "string",
        "resolution_strategy": "default_fill | projection | union_widening | type_coercion | reject",
        "justification": "string"
      }
    ]
  },
  "repaired_records": [
    {
      "original_record": {},
      "repaired_record": {},
      "repair_status": "success | partial | failed",
      "repair_log": ["string"]
    }
  ]
}

[OUTPUT_SCHEMA]

To adapt this template, start by replacing the core placeholders. [WRITER_SCHEMA] and [READER_SCHEMA] should contain the full Avro schema JSON, not just a name or ID. [FAILING_RECORDS] is a JSON array of the problematic records. The [CONSTRAINTS] placeholder is critical for safety; use it to inject business rules like "never drop a field marked as PII" or "prefer default_fill over projection for all non-nullable fields." The [OUTPUT_SCHEMA] placeholder allows you to enforce a strict contract for your downstream parser, such as adding required fields or enum values. If your use case is high-risk, add a final instruction to set a confidence_score for each repair and to flag any record for human review where the score is below a threshold.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Avro Schema Evolution Repair Prompt. Each placeholder must be populated before the prompt is assembled. Validation notes describe how the harness should verify the input before sending it to the model.

PlaceholderPurposeExampleValidation Notes

[WRITER_SCHEMA]

The Avro schema used by the producer to serialize the records. Must be a valid, parseable Avro schema JSON string.

{"type":"record","name":"User","fields":[{"name":"id","type":"int"},{"name":"email","type":"string"}]}

Parse check: must be valid JSON and valid Avro schema. Reject if schema contains recursive definitions or unsupported logical types without a conversion spec.

[READER_SCHEMA]

The Avro schema expected by the consumer. This is the target schema that the failing records must be made compatible with.

{"type":"record","name":"User","fields":[{"name":"id","type":"long"},{"name":"email","type":"string"},{"name":"phone","type":["null","string"],"default":null}]}

Parse check: must be valid JSON and valid Avro schema. Harness must confirm [READER_SCHEMA] differs from [WRITER_SCHEMA] in at least one field; otherwise the prompt is a no-op.

[FAILING_RECORDS]

A sample of records serialized with [WRITER_SCHEMA] that failed deserialization against [READER_SCHEMA]. Provided as a JSON array of objects.

Count check: must contain 1-20 records. Harness must verify each record conforms to [WRITER_SCHEMA] before passing to the prompt. If no records are available, set to an empty array and set [ERROR_MESSAGE] to a schema-only conflict description.

[ERROR_MESSAGE]

The exact deserialization error message produced by the Avro consumer or schema registry. Provides the model with the specific compatibility violation.

org.apache.avro.AvroTypeException: Found int, expecting long

Null allowed if the failure is a silent schema mismatch without a thrown exception. If present, must be a non-empty string. Harness should truncate stack traces to the first 3 frames to avoid token waste.

[COMPATIBILITY_MODE]

The schema evolution compatibility policy in effect. Controls which repair strategies the model is allowed to propose.

BACKWARD

Enum check: must be one of BACKWARD, FORWARD, FULL, BACKWARD_TRANSITIVE, FORWARD_TRANSITIVE, FULL_TRANSITIVE, or NONE. Harness must reject unknown values before prompt assembly.

[DEFAULT_POLICY]

Instructions for how the model should handle missing fields when projecting from writer to reader schema. Overrides the model's default behavior.

FILL_WITH_SCHEMA_DEFAULT

Enum check: must be one of FILL_WITH_SCHEMA_DEFAULT, FILL_WITH_TYPE_NULL, DROP_FIELD, or REJECT_RECORD. Harness must ensure this policy is consistent with [COMPATIBILITY_MODE].

[OUTPUT_SCHEMA]

The expected structure of the model's JSON response. Defines the fields the harness will parse after generation.

{"resolution_type":"string","corrected_records":"array","field_mapping":"array","unresolvable_fields":"array","confidence":"number"}

Parse check: must be a valid JSON Schema or a concise field-description object. Harness must validate the model's actual output against this schema and trigger a retry on mismatch.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Avro Schema Evolution Repair Prompt into a reliable data pipeline recovery workflow.

This prompt is designed to sit inside a dead-letter queue (DLQ) handler or a schema-registry compatibility check failure path. When a consumer fails to deserialize a record because the writer schema has diverged from the reader schema, the harness should catch the SchemaEvolutionException, extract the writer schema (from the message header or registry), the reader schema (from the consumer's local cache or registry), and a sample of the raw failing bytes. The prompt is then invoked to produce a compatibility resolution action and, if possible, a corrected record. The output is not a final answer but a structured repair instruction that the harness must validate and execute.

The harness must enforce a strict validation layer before any corrected record is forwarded downstream. After the model returns a resolution, the harness should: (1) parse the output against a fixed JSON schema that includes resolution_type (one of default_fill, projection, union_widening, reject), corrected_record, and explanation; (2) if resolution_type is not reject, serialize the corrected_record using the reader schema and confirm it succeeds without error; (3) run a semantic-diff check comparing the original writer-schema fields against the corrected record to ensure no non-nullable required fields were silently dropped without an explicit default_fill annotation; (4) log the model's explanation and the diff result to an audit table. If any validation step fails, the record should be routed to a manual-review quarantine topic, not retried automatically. For high-throughput pipelines, consider caching model responses for identical (writer_schema, reader_schema) pairs to avoid redundant LLM calls.

Model choice matters here. Use a model with strong structured-output capabilities and a context window large enough to hold both schemas plus the failing record sample. For most Avro schemas under 4KB, a model like gpt-4o or claude-3-5-sonnet with JSON mode enabled is sufficient. Set temperature to 0 to maximize deterministic repair behavior. The prompt should be called with a single retry on validation failure; if the second attempt also fails validation, escalate to the quarantine topic. Do not loop beyond two attempts, as schema evolution conflicts that the model cannot resolve in two tries are likely ambiguous and require human judgment. Wire the harness to emit a schema_evolution_resolution metric (tagged with resolution_type and success) so the team can monitor the rate of automated repairs versus quarantines over time.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, types, and validation rules for the Avro Schema Evolution Repair Prompt output. Use this contract to build a parser, validator, or retry harness that consumes the model response before applying corrections to records.

Field or ElementType or FormatRequiredValidation Rule

compatibility_resolution

string enum

Must be one of: default_fill, projection, union_widening, reject. Reject if value not in allowed set.

resolution_confidence

float

Must be between 0.0 and 1.0 inclusive. Parse as float and range-check. Flag if below 0.7 for human review.

resolved_writer_schema

valid Avro schema JSON

Must parse as valid JSON and pass Avro schema validation. Reject if schema is malformed or missing required type field.

field_mapping

array of objects

Each object must contain source_field, target_field, and action keys. action must be one of: keep, drop, default_fill, promote, demote. Validate array is non-empty.

corrected_records

array of objects

Each record must conform to resolved_writer_schema when validated. Reject if any record fails schema conformance check.

unmapped_fields

array of strings

List of writer schema fields with no reader schema counterpart. May be empty array. Validate each entry is a string matching a field name in the original writer schema.

repair_log

array of objects

Each entry must contain record_index, field_name, original_value, repaired_value, and repair_action. repair_action must be one of: default_fill, drop, type_promote, type_demote, null_fill. Validate record_index is a non-negative integer.

escalation_flag

boolean

Must be true if any record required a repair that loses information fidelity or if resolution_confidence is below 0.5. Harness must route escalated outputs to human review queue.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when using an LLM to repair Avro schema evolution conflicts, and how to guard against it in production.

01

Silent Data Loss on Projection

What to watch: The model drops fields present in the writer schema but absent from the reader schema without logging the decision. This causes silent data loss that downstream consumers never detect. Guardrail: Require the prompt to output a dropped_fields manifest and diff the input record count against the output field count in the harness. Reject any repair that removes fields without explicit annotation.

02

Type Widening with Precision Loss

What to watch: When the model widens an int to a long or a float to a double, it may introduce spurious decimal places or overflow values that violate downstream constraints. Guardrail: Add a post-repair validation step that re-serializes the corrected record with the reader schema and checks that round-trip values match the original within an epsilon. Flag any value that changes beyond the expected widening tolerance.

03

Default Fill Collision with Business Logic

What to watch: The model fills a missing required field with a plausible default (e.g., 0, `

04

Union Branch Ambiguity

What to watch: When the writer schema uses a union type (e.g., ["null", "string"]) and the reader schema narrows the union, the model may choose the wrong branch or produce a value that matches multiple branches ambiguously. Guardrail: Add a deterministic resolver in the harness that checks the model's chosen branch against the reader's accepted union members. If the chosen branch is invalid, retry with an explicit instruction to select only from the allowed set.

05

Enum Value Mapping Hallucination

What to watch: The writer schema contains an enum value (e.g., "PENDING_REVIEW") that does not exist in the reader schema's enum. The model invents a mapping (e.g., "IN_REVIEW") that is not a valid reader enum symbol. Guardrail: Validate every enum field in the corrected record against the reader schema's allowed symbols. On mismatch, retry with the reader's enum list injected into the prompt and instruct the model to choose the closest match or escalate if no match exists.

06

Record-Level Repair Without Batch Consistency

What to watch: The model repairs each record independently, producing inconsistent decisions across a batch (e.g., different default values for the same missing field on different rows). Guardrail: Process records in small batches (5-10) within a single prompt and instruct the model to apply the same resolution strategy to all records in the batch. Add a post-batch consistency check that verifies identical schema conflicts received identical resolutions.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality of an Avro schema evolution repair before shipping the prompt to production. Each row defines a pass standard, a failure signal, and a concrete test method.

CriterionPass StandardFailure SignalTest Method

Schema Compatibility

Output records conform to the provided [READER_SCHEMA] without parse errors.

Avro deserialization throws SchemaParseException or GenericDatumReader fails.

Validate all output records against [READER_SCHEMA] using a standard Avro library parser.

Semantic Field Preservation

All fields present in [WRITER_SCHEMA] are either mapped, default-filled, or explicitly projected with a documented reason.

A field from the writer schema is silently dropped without appearing in the output or the [UNMAPPED_FIELDS] list.

Diff the set of writer field names against the union of output field names and [UNMAPPED_FIELDS] entries.

Default Value Correctness

Fields missing in the writer record but required by the reader schema are filled with the default specified in [READER_SCHEMA] or a null sentinel.

A required reader field is filled with an incorrect type (e.g., string 'null' instead of a null value).

For each default-filled field, assert the output value's type matches the reader schema's field type definition.

Union Widening Safety

A writer field with a narrower type (e.g., int) is correctly promoted to a wider reader type (e.g., long) without data loss or overflow.

A numeric promotion results in a truncated or negative value due to incorrect sign extension.

Compare the numeric value of the writer field and the output field for a sample of 100 records; assert equality after widening.

Record-Level Repair Completeness

Every input record in [FAILING_RECORDS] produces exactly one output record or one structured rejection entry.

An input record is silently dropped, or a single input produces multiple output records without a merge annotation.

Assert that len(output_records) + len(rejection_entries) equals len([FAILING_RECORDS]).

Rejection Traceability

Rejected records include a [REJECTION_REASON] code and the original record payload.

A rejection entry is missing the [REJECTION_REASON] field or contains an empty string.

Parse each rejection entry and assert the presence of a non-empty [REJECTION_REASON] and a valid [ORIGINAL_RECORD].

Confidence Annotation

Each repair action is accompanied by a [CONFIDENCE] score between 0.0 and 1.0.

The [CONFIDENCE] field is missing, null, or outside the 0.0-1.0 range for any output record.

Assert that every output record and rejection entry contains a float [CONFIDENCE] field where 0.0 <= value <= 1.0.

Escalation Flag Integrity

Records with [CONFIDENCE] below [ESCALATION_THRESHOLD] are flagged with [REQUIRES_HUMAN_REVIEW] set to true.

A low-confidence record is not flagged, or a high-confidence record is incorrectly flagged.

Filter output records where [CONFIDENCE] < [ESCALATION_THRESHOLD] and assert [REQUIRES_HUMAN_REVIEW] is true for all of them.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add explicit compatibility rules, a required output schema, validation instructions, and a retry budget. Wire the prompt into a harness that validates corrected records against the reader schema before accepting them.

code
You are a schema evolution repair assistant for a production data pipeline. Your output must pass automated validation before ingestion.

## Compatibility Rules
- Prefer projection when the reader schema drops fields present in the writer schema.
- Prefer default-fill when the reader schema adds required fields not in the writer schema. Use type-appropriate defaults: "" for strings, 0 for numerics, null for optionals.
- Prefer union-widening when a field type changed (e.g., int to long, string to union{null, string}).
- Never invent data. Flag unresolvable records with "unresolvable": true and a reason.

## Input
Writer Schema: [WRITER_SCHEMA]
Reader Schema: [READER_SCHEMA]
Failing Records: [FAILING_RECORDS]
Retry Attempt: [RETRY_COUNT] of [MAX_RETRIES]

## Output Schema
Return valid JSON:
{
  "resolution": "default-fill" | "projection" | "union-widening",
  "compatibility_notes": ["string"],
  "corrected_records": [
    {
      "original_index": int,
      "record": object,
      "unresolvable": boolean,
      "unresolvable_reason": "string | null"
    }
  ]
}

Watch for

  • Silent format drift: the model may produce valid JSON that doesn't match the reader schema. Always validate post-response.
  • Missing human review: when unresolvable is true, the harness should quarantine the record, not silently drop it.
  • Retry loops: if the model produces invalid output on retry N, escalate rather than retrying indefinitely. Log every repair decision for audit.
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.