Inferensys

Prompt

Permission-Aware Index Selection Prompt

A practical prompt playbook for using Permission-Aware Index Selection 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

Defines the job, ideal user, required context, and constraints for the Permission-Aware Index Selection Prompt.

This prompt is designed for enterprise RAG teams managing access-controlled indexes where different users, roles, or tenants have permission to see different subsets of documents. The core job-to-be-done is routing a user query to the correct retrieval index based on the user's authorization profile, preventing both over-permission (retrieving documents the user should not see) and under-permission (failing to retrieve documents the user is entitled to access). The ideal user is an orchestration engineer or platform developer building a retrieval dispatch layer that must enforce data access policies before any retrieval call is made. Required context includes the user's role, clearance level, tenant scope, or group memberships, plus a mapping of available indexes to their access requirements.

Do not use this prompt when all users share the same access scope, when authorization is handled entirely at the application layer after retrieval, or when the index landscape is flat and unpartitioned. This prompt is also inappropriate for public-facing systems with no access controls, as the permission-checking overhead adds latency and complexity without benefit. If your system uses a single index with document-level filtering, prefer a metadata filter generation prompt instead. The prompt assumes that index-to-permission mappings are known and stable; if permissions change frequently during a session, you must invalidate cached routing decisions and re-evaluate.

Before deploying this prompt, ensure you have defined clear eval checks for both over-permission failures (the model routes a query to an index the user cannot access) and under-permission failures (the model fails to route to an index the user is authorized to use, causing missed results). Human review is required for any routing decision where the model's confidence falls below a defined threshold, or where the user's permission set is ambiguous or conflicting. Wire this prompt into a retrieval dispatch layer that logs every routing decision with the user's permission context, the selected index, and the confidence score, so that access violations can be audited and traced.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Permission-Aware Index Selection Prompt delivers value and where it introduces unacceptable risk. Use these cards to decide whether this prompt belongs in your retrieval dispatch layer.

01

Good Fit: Enterprise RAG with Access-Controlled Indexes

Use when: your retrieval system spans multiple indexes with distinct permission boundaries (role-based, tenant-scoped, or clearance-level). The prompt maps user identity claims to authorized index targets before retrieval executes. Guardrail: always resolve permissions server-side before passing them as [AUTHORIZED_INDEXES] to the prompt; never trust client-supplied scope.

02

Bad Fit: Single-Index or Public Corpora

Avoid when: all users share the same index or the corpus is public. The prompt adds latency and token cost without reducing risk. Guardrail: short-circuit the routing step when the authorized index list contains only one entry; skip the LLM call entirely and route directly.

03

Required Input: Resolved User Permissions

Risk: the prompt cannot enforce permissions it does not receive. If [AUTHORIZED_INDEXES] is empty, stale, or over-broad, the model may route to an index the user should not access. Guardrail: resolve permissions from an authoritative identity provider or access control system immediately before prompt assembly; never cache permission lists across sessions without revalidation.

04

Operational Risk: Over-Permission Leakage

Risk: the model selects an index the user is technically authorized to access but that is inappropriate for the query context, exposing sensitive documents. Guardrail: implement a post-routing validation step that checks the selected index against a query-to-index sensitivity map; log and alert on mismatches for review.

05

Operational Risk: Under-Permission Blocking

Risk: the model conservatively routes to a restricted subset of indexes, missing relevant documents the user is entitled to see. This degrades answer quality silently. Guardrail: monitor retrieval recall metrics per permission tier; if authorized-but-unselected indexes consistently contain relevant results, tune the prompt's routing instructions or add a confidence threshold that triggers broader search with post-retrieval filtering.

06

Latency and Cost Trade-Off

Risk: adding an LLM call before every retrieval increases end-to-end latency and token costs, especially for high-throughput systems. Guardrail: cache routing decisions for identical (query, permission-set) pairs with a short TTL; use a lightweight classification model instead of a full generation model when the index selection space is small and stable.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt that selects the correct access-controlled index for a user query based on their permissions, tenant scope, and clearance level.

This prompt acts as a permission-aware dispatch layer for enterprise RAG systems. It takes a user query, a list of available indexes with their access policies, and the user's current authorization context, then returns a single index selection decision with a confidence score and a justification. The template is designed to be wrapped in application code that enforces the decision—the model selects, the application gates. Never rely on the model alone to enforce access control; the prompt output should always be validated against a source-of-truth permissions store before retrieval executes.

text
You are an index selection router for an enterprise retrieval system. Your job is to choose the single most appropriate search index for a user query, respecting the user's permissions, role, tenant scope, and data clearance level.

## INPUT

User Query: [USER_QUERY]

User Authorization Context:
- User ID: [USER_ID]
- Roles: [USER_ROLES]
- Tenant IDs: [USER_TENANT_IDS]
- Clearance Level: [USER_CLEARANCE_LEVEL]
- Explicit Index Permissions: [USER_INDEX_PERMISSIONS]

Available Indexes (with access policies):
[AVAILABLE_INDEXES]

## TASK

1. Eliminate any index the user is not authorized to access based on role, tenant scope, clearance level, or explicit permissions.
2. From the remaining authorized indexes, select the single index best suited to answer the user query.
3. Consider: content domain match, query type fit (factual, procedural, comparative, etc.), freshness requirements, and entity coverage.
4. If no authorized index can reasonably answer the query, select "none" and explain why.
5. If multiple authorized indexes could work, choose the most specific one and note the alternatives.

## CONSTRAINTS

- Never select an index the user lacks permission to access, even if it would be the best semantic match.
- Prefer tenant-scoped indexes over global indexes when the user belongs to a specific tenant.
- If the query contains PII or sensitive terms, prefer indexes with higher clearance requirements.
- Do not fabricate index names or capabilities not listed in the available indexes.

## OUTPUT SCHEMA

Return a JSON object with these fields:
{
  "selected_index": string,        // index ID or "none"
  "confidence": number,            // 0.0 to 1.0
  "authorized_indexes_considered": [string],  // indexes that passed permission check
  "rejected_indexes": [             // indexes eliminated with reasons
    {
      "index": string,
      "reason": string
    }
  ],
  "justification": string,         // why this index was selected
  "alternative_indexes": [string], // runner-up authorized indexes
  "requires_human_review": boolean  // true if confidence < 0.7 or ambiguity detected
}

To adapt this prompt, replace the square-bracket placeholders with data from your application's authorization service and index registry. The [AVAILABLE_INDEXES] placeholder should be populated with a structured list of index objects, each containing at minimum an index_id, description, content_domain, required_roles, required_clearance_level, and tenant_scope field. If your system uses attribute-based access control (ABAC), extend the user authorization context with the relevant attributes. For high-security deployments, add a [RISK_LEVEL] parameter that adjusts the confidence threshold for requires_human_review. Always log the full prompt input and output for audit trails, and never cache index selection decisions across users with different permission sets.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Permission-Aware Index Selection Prompt. Each variable must be populated before the prompt is assembled and sent. Validation notes describe how to verify the input is safe and well-formed before it reaches the model.

PlaceholderPurposeExampleValidation Notes

[USER_QUERY]

The raw natural language question or search string from the end user.

Show me all open compliance violations for the West Campus facility.

Must be a non-empty string. Sanitize for prompt injection attempts. Truncate to 2000 characters before insertion.

[USER_ROLE]

The authenticated role or group membership of the requesting user.

compliance_officer

Must match an enum from your identity provider. Reject unknown or null roles. Map to canonical role name before insertion.

[USER_TENANT]

The tenant or organization scope the user belongs to.

tenant_west_region

Must be a non-empty string matching a valid tenant identifier in your access control system. Validate against tenant registry before use.

[USER_CLEARANCE_LEVEL]

The maximum data classification level the user is permitted to access.

confidential

Must be one of [public, internal, confidential, restricted]. Default to 'internal' if null. Reject values outside the enum.

[AVAILABLE_INDEXES]

A structured list of indexes with their access policies, content descriptions, and identifiers.

[{"id":"idx_legal_v1","scope":"legal_docs","min_clearance":"confidential","tenant_scope":"all"}]

Must be valid JSON array. Each entry requires id, scope, and min_clearance fields. Validate schema before insertion. Do not include indexes the user cannot possibly access.

[OUTPUT_SCHEMA]

The exact JSON schema the model must return, including selected indexes, confidence scores, and reasoning.

{"type":"object","properties":{"selected_indexes":{"type":"array"},"confidence":{"type":"number"}},"required":["selected_indexes","confidence"]}

Must be a valid JSON Schema object. Include required fields: selected_indexes, confidence, and rationale. Validate parseability before insertion.

[FALLBACK_INDEX]

The default index to use when no authorized index matches the query intent.

idx_general_knowledge_v2

Must be a valid index identifier from AVAILABLE_INDEXES. Must have the lowest clearance requirement. Reject if the fallback index requires clearance above the user's level.

[MAX_INDEXES]

The maximum number of indexes the model is allowed to select in a single response.

3

Must be an integer between 1 and 5. Default to 3 if not specified. Prevents over-fanout that degrades retrieval latency.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Permission-Aware Index Selection Prompt into a production RAG application with validation, retries, and audit logging.

This prompt operates as a pre-retrieval gate in your RAG pipeline. Before any vector or keyword search executes, the application must resolve the user's identity, roles, group memberships, and tenant scope from your auth layer (e.g., OAuth2 claims, JWT, session store). These resolved permissions become the [USER_PERMISSIONS] input. The prompt itself should run as a lightweight classification call—ideally on a fast, inexpensive model—because its job is to output a structured index selection decision, not to generate fluent text. The output is a JSON object containing the selected index name, a confidence score, and a fallback chain. Your application parses this JSON and uses it to route the retrieval request to the correct index backend.

Validation and enforcement happen in the application layer, not in the prompt. After the model returns an index selection, validate that the chosen index exists in your configured index registry and that the user's resolved permissions actually grant access to it. This is a hard server-side check: never trust the model's output as the sole access control decision. If the model selects an index the user cannot access, log the mismatch as a potential over-permission attempt, fall back to the highest-confidence permitted index from the fallback chain, and flag the event for review. Conversely, if the model fails to select an index the user should be able to access (under-permission), log it and attempt the fallback chain. Both failure modes should increment metrics you monitor: permission_override_count, fallback_triggered_count, and index_selection_confidence_below_threshold.

Retry logic should be minimal at the prompt level. If the model returns malformed JSON or a confidence score below your configured threshold (start with 0.7 and tune based on production data), do not blindly retry with the same inputs. Instead, route to a conservative default index scoped to the user's minimum guaranteed permissions, or escalate to a human review queue if the query context is high-risk. For multi-tenant SaaS applications, the [TENANT_SCOPE] input must be injected server-side from the authenticated session—never from the user's message—to prevent cross-tenant index leakage. Log every routing decision with: user_id, resolved_permissions_hash, query_fingerprint, selected_index, confidence, fallback_used, and timestamp. This audit trail is essential for compliance reviews and debugging permission boundary errors in production.

PRACTICAL GUARDRAILS

Common Failure Modes

Permission-aware index selection fails silently and dangerously. These are the most common production failure patterns and how to prevent them before they reach users.

01

Silent Over-Permission Leakage

What to watch: The prompt routes a query to an index the user should not access because the permission context was incomplete, stale, or ignored. The model confidently returns results from a restricted index without flagging the mismatch. Guardrail: Always inject explicit permission boundaries as structured constraints in the prompt, not as optional context. Validate the selected index against the user's authorized index list in application code before executing retrieval. Never rely solely on the model to enforce access control.

02

Under-Permission and Empty Result Sets

What to watch: The prompt conservatively excludes indexes the user is authorized to access, causing zero results or degraded answer quality. This happens when permission scopes are too narrow, role mappings are outdated, or the model overcorrects to avoid leakage. Guardrail: Log every index exclusion decision with the reason. Implement a post-retrieval check that compares authorized indexes against selected indexes and flags gaps. Use a secondary lightweight prompt to verify whether excluded indexes were incorrectly omitted.

03

Tenant Context Confusion in Multi-Tenant Deployments

What to watch: In multi-tenant systems, the prompt mixes tenant scopes or selects an index belonging to the wrong tenant because the tenant identifier was ambiguous, missing, or overridden by session state. Guardrail: Inject the tenant identifier as a non-negotiable constraint at the top of the prompt. Prefix every index name with the tenant scope in the selection schema. Add an application-layer assertion that the selected index belongs to the current tenant before executing any query.

04

Role Escalation Through Prompt Injection

What to watch: A user crafts a query that tricks the model into selecting a higher-privilege index by embedding role-like language, fake authorization tokens, or social engineering patterns in the input. Guardrail: Strip any role or permission language from user input before passing it to the selection prompt. Use a separate, immutable system-level permission block that cannot be overridden by user content. Test with adversarial inputs that attempt to impersonate admin, auditor, or cross-tenant roles.

05

Stale Permission Cache Mismatch

What to watch: The prompt uses cached or session-level permissions that have changed since the user's last authentication. Recently revoked access is not reflected, and the model selects an index the user no longer has rights to. Guardrail: Refresh permission context on every request or use short-lived tokens with explicit expiry. Include a permission freshness timestamp in the prompt and instruct the model to reject selections when the timestamp exceeds a threshold. Log mismatches between cached and live permission states.

06

Ambiguous Index Overlap Causing Wrong Selection

What to watch: Multiple indexes match the user's permissions and the query topic, but the model selects the wrong one because index descriptions are too similar, metadata is missing, or the selection criteria are underspecified. Guardrail: Provide clear, distinct descriptions for each index including content scope, freshness, and intended use. Include negative examples in the prompt showing when not to select each index. Add a confidence threshold and route low-confidence selections to a human review queue or fallback strategy.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the Permission-Aware Index Selection Prompt before shipping. Each criterion targets a specific failure mode common in access-controlled retrieval routing. Run these checks against a golden dataset of queries with known user permissions and expected index targets.

CriterionPass StandardFailure SignalTest Method

Correct Index Selection

Selected index matches the user's authorized index for the query domain

Index selected is not in the user's [AUTHORIZED_INDEXES] list

Assert selected_index is in authorized_indexes for each test case

Over-Permission Prevention

Never selects an index the user lacks access to, even if it is the best semantic match

Prompt selects a higher-clearance index than the user's [CLEARANCE_LEVEL] allows

Include adversarial queries that semantically match restricted indexes; verify rejection

Under-Permission Avoidance

Selects the most specific authorized index rather than defaulting to a public fallback

Prompt routes to a generic public index when a more specific authorized index exists

Check that selected_index is the most specific match within authorized_indexes, not just any match

Tenant Isolation

Index selection respects [TENANT_ID] and never crosses tenant boundaries

Prompt selects an index belonging to a different tenant than the user's [TENANT_ID]

Use queries with tenant-specific terminology; verify index tenant matches user tenant

Role-Aware Routing

Index selection reflects the user's [ROLE] when multiple indexes are authorized

Prompt ignores role and selects an index inappropriate for the user's function

Test with same query across different roles; verify different index selections where appropriate

Explicit Denial Handling

Returns a structured denial reason when no authorized index can serve the query

Prompt hallucinates an index or returns an empty response without explanation

Submit queries outside all authorized index scopes; verify structured denial with reason code

Confidence Calibration

Includes a confidence score that is low when query-index match is ambiguous

Confidence score is high for queries that span multiple index boundaries or are vague

Check that confidence_score < 0.7 for ambiguous queries and > 0.9 for clear matches

Fallback Ordering Validity

Provides an ordered fallback list of authorized indexes when primary confidence is below threshold

Fallback list includes unauthorized indexes or omits a better authorized alternative

Verify fallback_indexes array contains only authorized indexes and is ordered by relevance

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a hardcoded permission map. Replace [USER_ROLE] and [USER_TENANT] with static test values. Use a simple JSON output with selected_index and confidence fields. Skip formal schema validation during early testing.

code
You are an index router. The user has role [USER_ROLE] and tenant [USER_TENANT].
Available indexes: [INDEX_CATALOG]
Query: [QUERY]
Return JSON: {"selected_index": "...", "confidence": 0.0-1.0, "reasoning": "..."}

Watch for

  • Missing tenant scoping when indexes share names across tenants
  • Overly broad index selection when permission boundaries are fuzzy
  • No handling of queries that span multiple authorized indexes
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.