Inferensys

Prompt

Pre-Execution Deduplication Check Prompt

A practical prompt playbook for using the Pre-Execution Deduplication Check Prompt in production multi-agent workflows to prevent wasted compute and reconciliation debt.
Developer reviewing multi-agent chat interface on laptop, agent conversation logs visible, casual coding session at WeWork desk.
PROMPT PLAYBOOK

When to Use This Prompt

Understand the job, the user, and the constraints for the Pre-Execution Deduplication Check Prompt.

This prompt is designed for workflow orchestration engineers and AI platform builders who need to insert a guardrail immediately before an agent is dispatched to perform a task. Its primary job is to prevent wasted compute and reconciliation debt by checking a pending task against a registry of recently completed and currently in-flight tasks. The ideal user is someone building a task router, a multi-agent dispatcher, or an orchestration layer where the cost of duplicate execution is high—either in dollars, data mutation conflicts, or user experience degradation.

Use this prompt when you have a structured record of active and recent workstreams and a new task payload ready for assignment. The prompt requires, at minimum, a [PENDING_TASK] description and a [WORKSTREAM_REGISTRY] containing task summaries, statuses, and unique identifiers. It is most effective when the registry is a machine-readable list of objects, not a free-text log. The prompt performs a semantic comparison to determine if the new task is a duplicate of an existing one, returning a structured decision with a confidence score and a reference to the matched workstream. It is not a replacement for exact-match idempotency keys; it is a semantic safety net for catching near-duplicates that slip past deterministic checks.

Do not use this prompt for real-time, sub-millisecond dispatch loops where the latency of an LLM call is unacceptable. It is also unsuitable as the sole deduplication mechanism for financial transactions or other strictly ordered operations where an idempotency key and database constraint are mandatory. In high-risk domains like healthcare or finance, the prompt's output should be treated as a recommendation that requires a human-in-the-loop review or a deterministic fallback before blocking a task. Finally, this prompt is not designed to detect conflicts across tenant boundaries in multi-tenant systems; for that, pair it with a tenant-isolation check in the application layer.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Pre-Execution Deduplication Check Prompt delivers value and where it introduces risk. Use these cards to decide if this prompt belongs in your agent dispatch path.

01

Good Fit: High-Cost Agent Workflows

Use when: agent execution is expensive in compute, time, or API cost, and duplicate work directly wastes budget. Guardrail: Insert the deduplication check as a synchronous gate before dispatch. Cache fingerprints from recently completed tasks to make lookups fast and cheap relative to the agent run they protect.

02

Bad Fit: Real-Time Sub-Second Decisions

Avoid when: the deduplication lookup latency exceeds your dispatch SLA. Semantic comparison against an active workstream registry adds overhead. Guardrail: For latency-sensitive paths, use deterministic idempotency keys instead of semantic prompts. Reserve this prompt for workflows where the cost of duplication outweighs the lookup delay.

03

Required Inputs

What you need: a structured pending task payload (intent, entities, constraints), a registry of recently completed and in-flight task fingerprints, and a similarity threshold. Guardrail: Normalize task representations before comparison. Inconsistent field naming or missing entities across the registry will cause false negatives. Validate registry freshness before each check.

04

Operational Risk: False-Positive Blocking

What to watch: the prompt blocks a genuinely new task because it looks semantically similar to an existing one. This stalls legitimate work. Guardrail: Implement a confidence threshold and an override path. When the model is uncertain, route to a human or a lightweight clarification prompt rather than silently dropping the task. Log all blocked tasks with their similarity scores for audit.

05

Operational Risk: Stale Registry Poisoning

What to watch: completed or abandoned tasks remain in the active registry too long, causing new tasks to be incorrectly flagged as duplicates. Guardrail: Enforce TTL-based eviction on registry entries. Require agents to explicitly close their claims. Run a periodic reconciliation job that removes tasks with no heartbeat or expired claim windows before they corrupt deduplication decisions.

06

Cross-Tenant Isolation

What to watch: in multi-tenant systems, a task from Tenant A matches a fingerprint from Tenant B, causing a false duplicate block or, worse, cross-tenant data leakage. Guardrail: Scope the deduplication registry by tenant boundary. Include tenant ID as a required field in every fingerprint. Test explicitly for cross-tenant false positives in your eval harness before deployment.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for checking a pending task against recent and in-flight work to block duplicate execution before compute is spent.

This prompt template is the core of the pre-execution deduplication check. It is designed to be inserted into an orchestration layer immediately before an agent is dispatched. The prompt receives a pending task payload and a registry of recently completed and in-flight tasks, then returns a structured decision: proceed, block as duplicate, or flag for human review. The square-bracket placeholders let you swap in your own task schema, deduplication rules, and risk thresholds without rewriting the instruction logic.

text
You are a deduplication guard for an agent orchestration system. Your job is to prevent duplicate work before compute is spent.

You will receive a [PENDING_TASK] and a [TASK_REGISTRY] containing recently completed and in-flight tasks. Compare the pending task against the registry using semantic matching, not just keyword overlap.

[MATCHING_RULES]
- Two tasks are duplicates if they share the same core intent, primary entities, and desired outcome, even if phrased differently.
- A task is a partial duplicate if it overlaps significantly in scope but differs in parameters. Flag partial duplicates for review.
- Ignore differences in timestamp, request ID, or formatting.
- Respect [TENANT_ISOLATION_RULES]: never match tasks across tenant boundaries.

[OUTPUT_SCHEMA]
Return a single JSON object with these fields:
{
  "decision": "proceed" | "block" | "review",
  "confidence": 0.0-1.0,
  "matched_task_id": string | null,
  "match_type": "exact_duplicate" | "partial_overlap" | "none",
  "rationale": string,
  "recommended_action": string
}

[CONSTRAINTS]
- If confidence is below [MIN_CONFIDENCE_THRESHOLD], default to "review".
- If the pending task has an explicit [IDEMPOTENCY_KEY], check it against the registry's idempotency keys first.
- Do not fabricate matches. When in doubt, flag for review rather than blocking incorrectly.
- If the registry is empty or unavailable, return decision "proceed" with confidence 0.0 and note the missing data.

[EXAMPLES]
Example 1 - Exact duplicate:
Pending: {"intent": "summarize quarterly earnings for Q3 2024", "entities": ["Acme Corp"], "output_format": "executive brief"}
Registry: [{"id": "task-42", "intent": "summarize Q3 2024 earnings for Acme Corp", "status": "completed"}]
Output: {"decision": "block", "confidence": 0.97, "matched_task_id": "task-42", "match_type": "exact_duplicate", "rationale": "Same intent, entity, and output scope. Completed task covers this request.", "recommended_action": "Return cached result from task-42."}

Example 2 - Partial overlap:
Pending: {"intent": "analyze customer churn for enterprise segment", "entities": ["enterprise"], "time_range": "Q3 2024"}
Registry: [{"id": "task-38", "intent": "analyze customer churn across all segments", "entities": [], "time_range": "Q3 2024", "status": "in_flight"}]
Output: {"decision": "review", "confidence": 0.72, "matched_task_id": "task-38", "match_type": "partial_overlap", "rationale": "In-flight task covers a superset of the requested scope. Enterprise segment analysis may be derivable from the broader task.", "recommended_action": "Check if task-38 can satisfy the enterprise-specific request before dispatching a new agent."}

Now evaluate the pending task against the registry and return only the JSON object.

[PENDING_TASK]
[PENDING_TASK_PAYLOAD]

[TASK_REGISTRY]
[TASK_REGISTRY_PAYLOAD]

To adapt this template, replace the placeholder payloads with your actual task and registry data structures. The [MATCHING_RULES] section should reflect your organization's definition of duplicate work—tighten or loosen the semantic matching criteria based on your tolerance for false positives versus wasted compute. The [OUTPUT_SCHEMA] is the contract your orchestration layer will parse; keep the field names stable so downstream routing logic doesn't break. If your system uses idempotency keys, wire them into the [CONSTRAINTS] check as a fast path before running the full semantic comparison. For multi-tenant platforms, the [TENANT_ISOLATION_RULES] placeholder must be replaced with your actual tenant boundary logic to prevent cross-tenant data leakage through the deduplication check itself.

Before shipping this prompt, test it against a golden dataset of known duplicates, near-duplicates, and distinct tasks. Measure both false-positive blocks (which frustrate users by delaying legitimate work) and false-negative passes (which waste compute on redundant execution). If your task registry can grow large, add a retrieval step before this prompt to pre-filter the registry to candidate matches, keeping the prompt context within token limits. For high-stakes workflows where a false block could delay critical operations, route all "block" decisions with confidence below 0.95 to a human review queue rather than automatically rejecting them.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Pre-Execution Deduplication Check Prompt. Each variable must be populated before the prompt is sent to the model. Missing or malformed inputs will cause false negatives (duplicate execution) or false positives (blocked legitimate work).

PlaceholderPurposeExampleValidation Notes

[PENDING_TASK]

The task payload awaiting dispatch, including intent, entities, constraints, and requested action

{"intent": "update_billing_address", "entities": {"customer_id": "CUST-8821"}, "constraints": {"region": "eu-west-1"}}

Must be valid JSON with non-null intent and entities fields. Reject if payload exceeds 8KB or contains only free-text without structured fields.

[ACTIVE_WORKSTREAM_REGISTRY]

Array of recently completed and in-flight tasks with their fingerprints, statuses, and timestamps

[{"task_id": "T-4491", "fingerprint": "billing_address_update_CUST-8821", "status": "in_progress", "started_at": "2025-01-15T10:23:00Z"}]

Must be valid JSON array. Each entry requires task_id, fingerprint, and status fields. Reject if registry is older than the configured lookback window or contains entries without fingerprints.

[LOOKBACK_WINDOW_MINUTES]

Time window in minutes for considering recent tasks as potential duplicates

30

Must be a positive integer between 1 and 1440. Default to 60 if not specified. Values below 5 risk missing slow in-flight tasks; values above 240 increase false-positive risk from unrelated recurring work.

[SEMANTIC_MATCH_THRESHOLD]

Minimum similarity score (0.0 to 1.0) to classify two tasks as duplicates

0.85

Must be a float between 0.0 and 1.0. Values below 0.75 produce excessive false positives; values above 0.95 risk false negatives. Calibrate against a labeled duplicate-pair dataset before production use.

[TENANT_ISOLATION_KEY]

Identifier that scopes deduplication to a single tenant, preventing cross-tenant false matches

tenant_eu_production_01

Must be a non-empty string. Null or empty values must cause the prompt to abort with a configuration error. Cross-tenant deduplication without this key is a data leakage risk and must be blocked at the harness level.

[OUTPUT_SCHEMA]

Expected JSON structure for the deduplication decision, including match status, confidence, and matched task references

{"is_duplicate": true, "confidence": 0.94, "matched_task_ids": ["T-4491"], "rationale": "Same customer and intent within 10 minutes"}

Schema must include is_duplicate (boolean), confidence (float 0-1), matched_task_ids (array of strings), and rationale (string). Harness must validate output against this schema and retry on parse failure.

[MAX_CONFIDENCE_DELTA_FOR_HUMAN_REVIEW]

Confidence range around the threshold where decisions are flagged for human review instead of automatic blocking

0.10

Must be a float between 0.0 and 0.3. When confidence falls within [threshold - delta, threshold + delta], route to human review queue. Set to 0.0 to disable human review and accept automated decisions at all confidence levels.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the pre-execution deduplication check into an agent dispatch pipeline with validation, retries, and logging.

This prompt is designed to sit directly in the critical path of an agent task dispatcher. Before a task is assigned to a worker agent, the orchestrator calls this prompt with the pending task payload and a snapshot of the active workstream registry. The model returns a structured decision (DUPLICATE, UNIQUE, or AMBIGUOUS) along with a confidence score and a reference to the conflicting task ID. The orchestrator should treat this as a blocking gate: DUPLICATE results must halt dispatch and either discard the task or queue it for human review, while AMBIGUOUS results should trigger a secondary check or a short time-to-live (TTL) hold to see if the in-flight task completes.

To integrate this into a production harness, wrap the prompt call in a function with a strict timeout (e.g., 500ms for fast models, 2s for slower ones) because a deduplication check that takes longer than the task itself defeats the purpose. On timeout, the system should default to a safe fallback—either AMBIGUOUS with a log event or a configurable policy like 'allow dispatch but flag for post-hoc review.' Validate the model's output against a JSON schema that requires decision (enum of DUPLICATE, UNIQUE, AMBIGUOUS), confidence (float 0-1), matched_task_id (string or null), and rationale (string). If the output fails schema validation, retry once with a stricter prompt that includes the validation error. If it fails again, escalate to AMBIGUOUS and log the raw response for debugging.

For the workstream registry input, provide the model with a structured list of active and recently completed tasks (last N minutes, configurable by your SLA). Each entry should include a task ID, a semantic fingerprint or summary, the assigned agent, the status (IN_FLIGHT, COMPLETED, FAILED), and a timestamp. Avoid sending raw, unstructured task payloads; preprocess them into a canonical fingerprint using a companion prompt like the Agent Workstream Fingerprint Extraction Prompt. This keeps the deduplication prompt's context window small and its latency predictable. Log every decision—including the model, the fingerprint, the matched task, and the confidence score—to an append-only audit table. This log becomes the evidence trail for tuning the deduplication threshold and for diagnosing false positives that blocked legitimate work.

Model choice matters here. This prompt requires strong semantic comparison capabilities, so prefer models with high performance on sentence similarity and entailment tasks. For high-throughput pipelines, consider using a smaller, fine-tuned classifier model for the initial check and only escalating to a larger LLM when the classifier's confidence falls in a gray zone. If you're using a cloud LLM API, implement client-side retries with exponential backoff for transient errors (429, 503) but do not retry on schema validation failures more than once. Finally, build a lightweight eval harness that replays known duplicate and unique task pairs through the prompt weekly, measuring precision and recall against your labeled dataset. When the false-positive rate exceeds your operational threshold (e.g., 5%), investigate whether the fingerprint extraction step or the deduplication prompt itself needs tuning.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structured payload returned by the Pre-Execution Deduplication Check Prompt. Use this contract to validate the model's output before routing or blocking a task.

Field or ElementType or FormatRequiredValidation Rule

deduplication_decision

enum: DUPLICATE | UNIQUE | UNCERTAIN

Must be exactly one of the three enum values. Reject any other string.

matched_task_id

string or null

If decision is DUPLICATE, must be a non-empty string matching an existing task ID. If UNIQUE, must be null. If UNCERTAIN, may be a suspected match ID or null.

confidence_score

float between 0.0 and 1.0

Must be a valid float. Parse check required. If decision is UNIQUE and score < 0.90, flag for human review.

match_rationale

string

Must be a non-empty string summarizing the semantic overlap or lack thereof. If decision is DUPLICATE, must cite specific overlapping fields.

overlapping_fields

array of strings

Must be a valid JSON array. If decision is UNIQUE, must be an empty array. If DUPLICATE, must contain at least one field name from [INPUT].

recommended_action

enum: PROCEED | BLOCK | REVIEW

Must be exactly one of the three enum values. PROCEED only allowed when decision is UNIQUE. BLOCK only allowed when decision is DUPLICATE. REVIEW allowed for UNCERTAIN.

lookup_latency_ms

integer or null

If provided by the harness, must be a non-negative integer. Null if lookup latency is not measured or not applicable.

checked_against_count

integer

Must be a non-negative integer representing the number of recent or in-flight tasks compared. A value of 0 requires the decision to be UNIQUE or UNCERTAIN, never DUPLICATE.

PRACTICAL GUARDRAILS

Common Failure Modes

Pre-execution deduplication checks stop duplicate agent work before compute is spent. These are the most common failure modes when the check itself fails, and how to guard against them.

01

Semantic False Negatives

What to watch: Two tasks that are semantically identical but phrased differently (e.g., 'update user 42's email' vs. 'change contact info for ID 42') fail to match, allowing duplicate execution. This happens when similarity thresholds are too strict or embeddings don't capture domain-specific equivalence. Guardrail: Calibrate similarity thresholds against a labeled dataset of known duplicates and near-duplicates from your domain. Use a two-stage check: fast vector similarity followed by an LLM-based binary match decision for borderline cases.

02

False-Positive Blocking

What to watch: Legitimate distinct tasks are incorrectly flagged as duplicates and blocked. For example, 'update user 42's email' and 'update user 42's phone' share entities but are different operations. Over-blocking stalls workflows and erodes trust in the deduplication system. Guardrail: Require both intent and entity match for a block decision. Add an override mechanism where blocked tasks can be force-released with an audit reason. Monitor the false-positive rate by sampling blocked tasks and reviewing them manually.

03

Stale In-Flight Task Registry

What to watch: The deduplication check queries a registry of in-flight tasks, but completed or abandoned tasks aren't evicted. New tasks that legitimately repeat a previously completed operation get blocked. Conversely, tasks that have been silently abandoned still appear active and prevent re-dispatch. Guardrail: Implement TTL-based eviction for in-flight task entries with a heartbeat refresh from the executing agent. Mark tasks as terminal (completed, failed, cancelled) and exclude them from the active deduplication scope. Alert on tasks that exceed their expected execution window without a heartbeat.

04

Cross-Tenant Leakage

What to watch: In multi-tenant systems, a deduplication check scoped incorrectly matches a task from Tenant A against Tenant B's in-flight tasks, either blocking Tenant B's legitimate work or leaking the fact that Tenant A is performing a similar operation. Guardrail: Always partition the deduplication index by tenant ID as a hard filter before any semantic comparison. Add a pre-check assertion that the tenant context is present and valid. Test explicitly with identical payloads across tenant boundaries to confirm isolation.

05

Lookup Latency Exceeding Dispatch Budget

What to watch: The deduplication check adds unacceptable latency to the dispatch path, especially when the in-flight registry grows large or the similarity computation is expensive. If the check takes longer than the expected task execution time, it defeats the purpose of saving compute. Guardrail: Set a strict latency budget for the deduplication check (e.g., 200ms p99). Use approximate nearest-neighbor search with early termination. If the check times out, apply a configurable default policy (allow or block) and log the timeout for investigation.

06

Idempotency Key Collision

What to watch: The system generates idempotency keys from task payloads to prevent duplicate side effects, but key generation is non-deterministic or too coarse-grained. Two different tasks produce the same key and one is incorrectly discarded, or the same task produces different keys on retry and executes twice. Guardrail: Generate idempotency keys deterministically from a canonicalized representation of the task intent and target entities. Hash the canonical form, not the raw input. Validate key stability by re-generating keys from perturbed but semantically identical inputs and confirming they match.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the Pre-Execution Deduplication Check Prompt before deploying it in a production agent dispatch pipeline. Each criterion targets a specific failure mode that wastes compute or creates reconciliation debt.

CriterionPass StandardFailure SignalTest Method

Semantic Duplicate Recall

Flags >=95% of tasks that are semantically equivalent to an active or recently completed task, even when wording differs significantly.

A task with identical intent and entities but different phrasing is dispatched as new work.

Run a golden set of 50 known duplicate pairs through the prompt. Measure recall against human-labeled ground truth.

False-Positive Suppression

Incorrectly blocks <5% of genuinely unique tasks. A false positive is defined as a task with a distinct intent or distinct primary entity.

A novel task is incorrectly matched to an unrelated active workstream and blocked from dispatch.

Run a golden set of 50 known unique tasks against a populated active workstream registry. Measure the false-positive rate.

Cross-Tenant Isolation

Never matches a task from Tenant A to a workstream owned by Tenant B. Tenant boundary is provided in [TENANT_ID].

A task from one tenant is blocked because it matches a workstream in a different tenant.

Submit tasks with identical intent but different [TENANT_ID] values. Confirm the prompt returns duplicate: false.

Lookup Latency Tolerance

The prompt correctly interprets the [LOOKUP_WINDOW_MINUTES] constraint and ignores workstreams with a completed_at timestamp outside the window.

A task is blocked by a workstream that completed 2 hours ago when the lookup window is set to 30 minutes.

Seed the registry with a workstream completed 60 minutes ago. Set [LOOKUP_WINDOW_MINUTES] to 30. Confirm the prompt returns duplicate: false.

Output Schema Compliance

Returns valid JSON matching the [OUTPUT_SCHEMA] exactly, including all required fields: duplicate, matched_workstream_id, confidence, rationale.

The response is missing a required field, uses an incorrect type, or includes extra fields not in the schema.

Parse the output with a strict JSON schema validator. Run 20 varied inputs and confirm 100% schema compliance.

Confidence Score Calibration

Confidence scores correlate with match quality. Scores >=0.9 indicate near-certain duplicates. Scores <0.5 indicate likely unique tasks.

A clear duplicate receives a confidence score of 0.4, or a clearly unique task receives a score of 0.95.

Plot confidence scores against human-labeled match quality for 100 test cases. Check that the score distribution separates duplicates from unique tasks.

Idempotency Key Stability

When the prompt is used to generate an idempotency key from the task payload, the same logical task always produces the same key.

Two identical task payloads submitted 5 minutes apart produce different idempotency keys.

Submit the same task payload 10 times. Confirm the generated idempotency key is identical across all submissions.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a simple in-memory registry of recent tasks. Replace the structured fingerprint extraction with a direct similarity instruction: "Compare [PENDING_TASK] against [RECENT_TASKS] and return DUPLICATE or UNIQUE with a brief reason." Skip idempotency key generation and rely on the model's judgment alone.

Watch for

  • Semantic false positives when tasks share keywords but differ in intent
  • No latency budget enforcement; model may overthink comparisons
  • Registry grows unbounded without eviction logic
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.