Skip to content

Implement context-aware synthetic selection, usage limits, and automatic failover #1991

Closed

Description

@propr-dev

Context

Once synthetic configuration exists, every LLM call that targets a virtual identity must resolve to a concrete direct agent and model. Selection must account for enabled state, strict priority tiers, configured usage ceilings, context-window requirements, and members already attempted for that call.

The physical model must be selected before context-sensitive work calculates a prompt budget. Otherwise a plan, review, or indexing batch could be assembled for a large-context model and later routed to a smaller model that cannot accept it.

A failed physical execution must automatically retry through normal selection logic while excluding members already attempted for that call.

Requirements

  • Add a central synthetic routing service; do not duplicate selection logic in planners, workers, reviews, chat, and indexing.
  • Keep the requested virtual identity stable in task records, labels, and branches.
  • Record the physical agent/model for each attempt in LLM-log metadata and task history.
  • Implement strict priority tiers:
    • Determine all currently eligible members.
    • Keep only members at the highest eligible priority.
    • Apply the configured strategy within that tier.
    • Consider priority-zero members only when no higher-priority member is eligible.
  • Implement deterministic round-robin with an atomic persisted cursor per synthetic model.
  • Implement usage-based selection by choosing the member with the most remaining normalized headroom within the highest priority tier.
  • Treat usage data as unavailable when no fresh alias-specific snapshot exists. A member with an applicable usage cap must not be selected from unknown or stale data.
  • Keep uncapped round-robin pools independent of Agent Tank.
  • Filter candidates whose context window cannot accommodate the required prompt plus output/runtime reserve.
  • Introduce a call-scoped selection session that pins the first physical model early and reuses the required-token constraint for retries.
  • On failure, exclude the failed member and select again. Each physical member may be attempted at most once per logical call.
  • Do not retry explicit cancellation, security-policy violations, invalid user configuration, or prompt-too-large errors.
  • Preserve task/worktree identity across implementation retries, but create a unique execution/container ID per attempt.
  • Stop with an aggregated SyntheticPoolExhaustedError when no eligible members remain.

Usage Data Contract

Usage-based routing requires usage snapshots keyed by direct agent alias, not merely provider name. This distinction is essential when two Claude or Codex aliases use different subscriptions.

The existing Agent Tank integration may continue displaying provider-level information, but it must not apply a provider-global value to several direct aliases as if it were account-specific. Only a snapshot collected or explicitly mapped for a direct alias may satisfy a synthetic member's usage cap. Unknown data makes that capped member temporarily ineligible and must be visible in diagnostics.

Context-Sensitive Integration Points

  • Planner context and plan generation: begin a routing session before calculating model hard limits and token budgets.
  • PR review and review-context scouting: select before resolveReviewContextTokenBudget and prompt construction.
  • Repository indexing: select before calculating file/directory batch limits so physical-model overrides apply correctly.
  • Repository chat, improvements, lightweight analysis, and playground chat: route immediately before invoking Agent.analyze.
  • Implementation and follow-up tasks: retain the virtual task identity while retrying physical executions within the task attempt.

Acceptance Criteria

  • Round-robin selection rotates fairly within the highest eligible priority tier and persists across worker processes.
  • A priority-100 member is selected before priority-0 members whenever it is eligible.
  • When the priority-100 member is disabled, quota-capped, context-ineligible, failed earlier in the call, or unavailable, the priority-0 fallback is selected.
  • Usage-based selection chooses the greatest remaining normalized headroom without exceeding any configured cap.
  • A capped member with stale or missing alias-specific usage data is not selected.
  • An uncapped member remains usable when Agent Tank is disabled.
  • Planning, review, and indexing tests prove physical selection occurs before their token or batch budget is calculated.
  • A failed member is attempted once, excluded, and followed by the next selection.
  • Cancellation and context-limit failures are not retried.
  • Exhaustion errors list each attempted or rejected member and its reason without exposing credentials.
  • LLM logs contain virtual identity, physical identity, member ID, call ID, attempt number, and selection reason.
  • Existing direct-agent behavior remains unchanged when the requested alias is not synthetic.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Aug 29, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    Use a two-layer design. A pure selector evaluates candidates and is easy to test exhaustively. A routing service supplies live direct-agent state, context limits, usage snapshots, and an atomic cursor, then creates a call-scoped session for execution and failover.

    Physical resolution is deliberately deferred until the LLM-call boundary, but context-sensitive callers open that boundary before calculating budgets. Flattening pools when tasks are queued was rejected because availability and quota can change while a job waits. Selecting only inside the Docker adapter was also rejected because context could already have been oversized by then.

    Retry orchestration wraps only the agent call. GitHub comments, commits, pushes, PR creation, and other worker finalization must remain outside the retry loop so a failed model cannot duplicate deterministic side effects.

    File: packages/core/src/agents/synthetic/syntheticSelector.ts (new file)

    Why this file: This pure module contains the complete selection semantics without database, Redis, Agent Tank, or registry dependencies. Keeping it pure makes priority, quota, context, and exclusion behavior deterministic and independently testable.

    import type {
      SyntheticModelConfig,
      SyntheticModelMember,
    } from '@propr/shared';
    
    export interface SyntheticMemberUsageSnapshot {
      sessionPercent?: number;
      weeklyPercent?: number;
      observedAt: string;
    }
    
    export interface SyntheticMemberRuntimeState {
      member: SyntheticModelMember;
      directAgentEnabled: boolean;
      modelSupported: boolean;
      contextWindowTokens: number;
      usage?: SyntheticMemberUsageSnapshot;
    }
    
    export type SyntheticIneligibilityReason =
      | 'member_disabled'
      | 'direct_agent_disabled'
      | 'model_unsupported'
      | 'already_attempted'
      | 'context_too_small'
      | 'usage_unknown'
      | 'session_cap_reached'
      | 'weekly_cap_reached';
    
    export interface SyntheticCandidateDiagnostic {
      memberId: string;
      directAgentAlias: string;
      model: string;
      eligible: boolean;
      reason?: SyntheticIneligibilityReason;
    }
    
    export interface SyntheticSelectionInput {
      model: SyntheticModelConfig;
      states: SyntheticMemberRuntimeState[];
      excludedMemberIds: ReadonlySet<string>;
      requiredContextTokens: number;
      cursor: number;
      usageFreshnessMs: number;
      nowMs?: number;
    }
    
    export interface SyntheticSelectionResult {
      selected?: SyntheticModelMember;
      nextCursor: number;
      reason?: string;
      diagnostics: SyntheticCandidateDiagnostic[];
    }
    
    function usageIsFresh(
      usage: SyntheticMemberUsageSnapshot | undefined,
      nowMs: number,
      freshnessMs: number,
    ): usage is SyntheticMemberUsageSnapshot {
      if (!usage) return false;
      const observedAt = Date.parse(usage.observedAt);
      return Number.isFinite(observedAt) && nowMs - observedAt <= freshnessMs;
    }
    
    function ineligibilityReason(
      state: SyntheticMemberRuntimeState,
      input: SyntheticSelectionInput,
      nowMs: number,
    ): SyntheticIneligibilityReason | undefined {
      const { member } = state;
      if (!member.enabled) return 'member_disabled';
      if (!state.directAgentEnabled) return 'direct_agent_disabled';
      if (!state.modelSupported) return 'model_unsupported';
      if (input.excludedMemberIds.has(member.id)) return 'already_attempted';
      if (state.contextWindowTokens < input.requiredContextTokens) return 'context_too_small';
    
      const limits = member.usageLimits;
      const hasUsageLimit = limits?.sessionMaxPercent !== undefined
        || limits?.weeklyMaxPercent !== undefined;
      if (!hasUsageLimit) return undefined;
    
      // Unknown usage must not be interpreted as zero. That would silently overrun
      // an operator's configured allowance after Agent Tank becomes unavailable.
      if (!usageIsFresh(state.usage, nowMs, input.usageFreshnessMs)) {
        return 'usage_unknown';
      }
      if (
        limits?.sessionMaxPercent !== undefined
        && (state.usage.sessionPercent === undefined
          || state.usage.sessionPercent >= limits.sessionMaxPercent)
      ) {
        return state.usage.sessionPercent === undefined
          ? 'usage_unknown'
          : 'session_cap_reached';
      }
      if (
        limits?.weeklyMaxPercent !== undefined
        && (state.usage.weeklyPercent === undefined
          || state.usage.weeklyPercent >= limits.weeklyMaxPercent)
      ) {
        return state.usage.weeklyPercent === undefined
          ? 'usage_unknown'
          : 'weekly_cap_reached';
      }
      return undefined;
    }
    
    function normalizedHeadroom(state: SyntheticMemberRuntimeState): number {
      const limits = state.member.usageLimits;
      const values: number[] = [];
      if (limits?.sessionMaxPercent !== undefined) {
        values.push(
          (limits.sessionMaxPercent - (state.usage?.sessionPercent ?? limits.sessionMaxPercent))
          / limits.sessionMaxPercent,
        );
      }
      if (limits?.weeklyMaxPercent !== undefined) {
        values.push(
          (limits.weeklyMaxPercent - (state.usage?.weeklyPercent ?? limits.weeklyMaxPercent))
          / limits.weeklyMaxPercent,
        );
      }
      // An uncapped member has full routing headroom. Priority is evaluated first,
      // so this cannot jump over a higher-priority capped member.
      return values.length > 0 ? Math.min(...values) : 1;
    }
    
    export function selectSyntheticMember(
      input: SyntheticSelectionInput,
    ): SyntheticSelectionResult {
      const nowMs = input.nowMs ?? Date.now();
      const diagnostics: SyntheticCandidateDiagnostic[] = [];
      const eligible: SyntheticMemberRuntimeState[] = [];
    
      for (const state of input.states) {
        const reason = ineligibilityReason(state, input, nowMs);
        diagnostics.push({
          memberId: state.member.id,
          directAgentAlias: state.member.directAgentAlias,
          model: state.member.model,
          eligible: reason === undefined,
          ...(reason ? { reason } : {}),
        });
        if (!reason) eligible.push(state);
      }
    
      if (eligible.length === 0) {
        return { nextCursor: input.cursor, diagnostics };
      }
    
      // Strict tiers make priority zero a real fallback rather than a small random
      // chance of taking work away from the configured primary subscription.
      const highestPriority = Math.max(...eligible.map(state => state.member.priority));
      let tier = eligible.filter(state => state.member.priority === highestPriority);
    
      if (input.model.strategy === 'usage_based') {
        const bestHeadroom = Math.max(...tier.map(normalizedHeadroom));
        tier = tier.filter(state => normalizedHeadroom(state) === bestHeadroom);
      }
    
      // A persisted cursor also breaks equal-headroom ties, preventing the first
      // configured member from receiving every usage-based call.
      const selectedIndex = input.cursor % tier.length;
      const selected = tier[selectedIndex].member;
      return {
        selected,
        nextCursor: (selectedIndex + 1) % tier.length,
        reason: input.model.strategy === 'usage_based'
          ? `priority ${highestPriority}, greatest usage headroom`
          : `priority ${highestPriority}, round-robin position ${selectedIndex + 1}/${tier.length}`,
        diagnostics,
      };
    }

    File: packages/core/src/agents/synthetic/syntheticRuntimeState.ts (new file)

    Why this file: Multiple workers can select the same pool concurrently. An in-memory cursor would restart on deployment and let separate processes repeatedly choose the same subscription. Persist and advance a cursor transactionally using the same conflict-safe pattern as summarization runtime state.

    Implement these exports:

    export interface SyntheticRuntimeState {
      cursors: Record<string, number>;
      latestUsageByDirectAlias: Record<string, {
        sessionPercent?: number;
        weeklyPercent?: number;
        observedAt: string;
      }>;
    }
    
    // The key must include both configuration ID and virtual model ID so renaming an
    // alias does not reset fairness and different virtual models do not share turns.
    export function syntheticCursorKey(agentId: string, modelId: string): string {
      return JSON.stringify([agentId, modelId]);
    }
    
    export async function readAndAdvanceSyntheticCursor(
      agentId: string,
      modelId: string,
      select: (cursor: number) => { selectedMemberId?: string; nextCursor: number },
    ): Promise<{ selectedMemberId?: string; cursor: number }>;
    
    export async function recordSyntheticUsageSnapshot(
      directAgentAlias: string,
      snapshot: {
        sessionPercent?: number;
        weeklyPercent?: number;
        observedAt: string;
      },
    ): Promise<void>;

    Implement readAndAdvanceSyntheticCursor in one database transaction. On SQLite, use compare-and-swap against the original system_configs.value, matching configManagerSummarization.ts; on other databases use FOR UPDATE. Advance the cursor only when a member is actually selected.

    File: packages/core/src/agents/synthetic/SyntheticRoutingService.ts (new file)

    Why this file: This service joins saved pool configuration with the direct AgentRegistry, context limits, usage snapshots, and cursor store. Callers receive a physical lease without learning selection details.

    The public surface should be:

    export interface SyntheticPhysicalLease {
      callId: string;
      attempt: number;
      virtualAgentAlias: string;
      virtualModel: string;
      memberId: string;
      physicalAgentAlias: string;
      physicalModel: string;
      physicalContextWindowTokens: number;
      selectionReason: string;
    }
    
    export interface SyntheticCallSession {
      readonly virtualAgentAlias: string;
      readonly virtualModel: string;
      readonly callId: string;
      readonly requiredContextTokens: number;
      selectNext(): Promise<SyntheticPhysicalLease>;
      exclude(memberId: string, reason: string): void;
      diagnostics(): ReadonlyArray<unknown>;
    }
    
    export class SyntheticPoolExhaustedError extends Error {
      readonly code = 'SYNTHETIC_POOL_EXHAUSTED';
      constructor(
        message: string,
        readonly attempts: ReadonlyArray<{
          memberId: string;
          physicalAgentAlias: string;
          physicalModel: string;
          error: string;
        }>,
        readonly candidateDiagnostics: ReadonlyArray<unknown>,
      ) {
        super(message);
        this.name = 'SyntheticPoolExhaustedError';
      }
    }
    
    export async function createSyntheticCallSession(options: {
      configuredIdentity: string;
      requiredContextTokens: number;
      callId?: string;
    }): Promise<SyntheticCallSession | null>;

    Return null when the configured alias is direct. That keeps the direct path byte-for-byte compatible. Resolve member context limits with the existing getModelHardLimit/model metadata path and load only direct agents from AgentRegistry.

    File: packages/core/src/agents/synthetic/runSyntheticCall.ts (new file)

    Why this file: Every execution surface needs identical failover behavior. This wrapper ensures retries exclude failed members and that only the agent invocation is repeated.

    import { ExecutionAbortedError } from '../../claude/docker/dockerExecutor.js';
    import { ContextTokenLimitError, SecurityException } from '../../services/context/index.js';
    import {
      SyntheticPoolExhaustedError,
      type SyntheticCallSession,
      type SyntheticPhysicalLease,
    } from './SyntheticRoutingService.js';
    
    export interface SyntheticAttemptObserver {
      onAttemptStarted?(lease: SyntheticPhysicalLease): Promise<void> | void;
      onAttemptFailed?(
        lease: SyntheticPhysicalLease,
        error: unknown,
      ): Promise<void> | void;
    }
    
    function retryableExecutionError(error: unknown): boolean {
      // These failures cannot be corrected by another provider and retrying them
      // would ignore an explicit stop or a deterministic safety boundary.
      if (error instanceof ExecutionAbortedError) return false;
      if (error instanceof ContextTokenLimitError) return false;
      if (error instanceof SecurityException) return false;
      const code = (error as { code?: unknown })?.code;
      return ![
        'INVALID_SYNTHETIC_CONFIG',
        'EXECUTION_ABORTED',
        'SECURITY_POLICY_VIOLATION',
        'PROMPT_TOO_LARGE',
      ].includes(typeof code === 'string' ? code : '');
    }
    
    export async function runSyntheticCall<T>(options: {
      session: SyntheticCallSession;
      execute: (lease: SyntheticPhysicalLease) => Promise<T>;
      isFailedResult: (result: T) => boolean;
      resultError: (result: T) => string;
      observer?: SyntheticAttemptObserver;
    }): Promise<T> {
      const attempts: Array<{
        memberId: string;
        physicalAgentAlias: string;
        physicalModel: string;
        error: string;
      }> = [];
    
      while (true) {
        let lease: SyntheticPhysicalLease;
        try {
          lease = await options.session.selectNext();
        } catch (error) {
          if (error instanceof SyntheticPoolExhaustedError) {
            throw new SyntheticPoolExhaustedError(
              error.message,
              attempts,
              options.session.diagnostics(),
            );
          }
          throw error;
        }
    
        await options.observer?.onAttemptStarted?.(lease);
        try {
          const result = await options.execute(lease);
          if (!options.isFailedResult(result)) return result;
    
          const message = options.resultError(result);
          attempts.push({
            memberId: lease.memberId,
            physicalAgentAlias: lease.physicalAgentAlias,
            physicalModel: lease.physicalModel,
            error: message,
          });
          options.session.exclude(lease.memberId, message);
          await options.observer?.onAttemptFailed?.(lease, new Error(message));
        } catch (error) {
          if (!retryableExecutionError(error)) throw error;
          const message = error instanceof Error ? error.message : 'Agent execution failed';
          attempts.push({
            memberId: lease.memberId,
            physicalAgentAlias: lease.physicalAgentAlias,
            physicalModel: lease.physicalModel,
            error: message,
          });
          // Excluding before the next selection guarantees a failing subscription
          // is never retried in the same logical call, even if it remains highest priority.
          options.session.exclude(lease.memberId, message);
          await options.observer?.onAttemptFailed?.(lease, error);
        }
      }
    }

    File: packages/core/src/agents/impl/utils/usageTrackingWrapper.ts

    Why this file: This is the existing pre/post-call usage boundary. It is the correct place to record a fresh snapshot, but only when the snapshot is attributable to the direct alias whose credentials produced it.

    Add an optional directAgentAlias and onUsageSnapshot callback to the wrapper options. After a successful post-call probe, normalize session and weekly absolute percentages and call recordSyntheticUsageSnapshot. Do not write a snapshot when the integration returns only a provider-global record that cannot be mapped to the direct alias.

    Include a reasoning comment explaining that copying one provider value to several aliases would break the multiple-subscription use case and could deplete the wrong account.

    File: packages/core/src/config/configuredModel.ts

    Why this file: This function should continue resolving the public configured identity, including a synthetic identity, without flattening it prematurely.

    Update plain-model resolution so resolveLlmLabel can discover virtual catalog models. Preserve already-qualified identities. Add a comment that physical resolution belongs to createSyntheticCallSession, after live quota and availability are known.

    Files: context-sensitive call sites

    Why these files: They must open a routing session before computing budgets, while ordinary direct calls continue down their current path.

    Apply the following sequence in:

    • packages/core/src/services/taskPlanning/llmCalling.ts
    • src/jobs/reviewContextScout.ts
    • src/jobs/prReviewRunner.ts
    • the repository indexing batch coordinator that calls processSingleBatch and processDirectoryBatch
    // Select the physical model before sizing context because a synthetic model may
    // contain members with different hard limits. The same required-token floor is
    // retained if failover selects another member later.
    const routingSession = await createSyntheticCallSession({
      configuredIdentity,
      requiredContextTokens: estimatedInputTokens + outputAndRuntimeReserve,
      callId: correlationId,
    });
    
    const firstLease = routingSession ? await routingSession.selectNext() : null;
    const effectiveAgentAlias = firstLease?.physicalAgentAlias ?? configuredAgentAlias;
    const effectiveModel = firstLease?.physicalModel ?? configuredModel;
    const effectiveHardLimit = firstLease?.physicalContextWindowTokens
      ?? getModelHardLimit(effectiveModel);
    
    // Build and validate the prompt against the selected physical limit. A retry
    // session must exclude candidates unable to fit the final measured token count.

    Refactor SyntheticCallSession to permit the initial lease to be passed into runSyntheticCall without selecting twice. After the final prompt is built, update or assert the session's required-token floor using measured tokens plus reserve.

    For indexing, apply physical getSummarizationBatchLimitOverride before constructing each batch. The selected physical model, not the virtual ID, determines model-specific batch caps.

    File: task execution worker entry point

    Why this file: Implementation tasks need call-level failover while commits, pushes, and PR creation remain single-run finalization steps.

    Wrap only the existing direct agent execution call with runSyntheticCall. For each lease:

    • resolve the direct agent from AgentRegistry;
    • pass lease.physicalModel to it;
    • generate a new createContainerExecutionId(taskId);
    • leave the task's public agent/model fields set to the virtual identity;
    • append attempt metadata to task history;
    • run existing finalization once after a successful physical result.

    Retain the task-scoped worktree between attempts. Add an explicit retry instruction telling the next model that an earlier execution failed and that it must inspect existing workspace changes before continuing. This preserves potentially useful partial edits; automatically resetting the worktree was rejected because it could destroy valid uncommitted work without knowing whether the previous agent failed before or after editing.

    File: packages/core/src/utils/llmLogger.ts

    Why this file: Operators need to understand which subscription actually handled a virtual call. Add optional routing metadata without replacing existing agentAlias and modelUsed fields.

    export interface SyntheticRoutingLogMetadata {
      syntheticAgentAlias: string;
      syntheticModel: string;
      physicalAgentAlias: string;
      physicalModel: string;
      syntheticMemberId: string;
      syntheticCallId: string;
      syntheticAttempt: number;
      syntheticSelectionReason: string;
    }

    Merge these fields into existing metadata for synthetic attempts. Do not log config paths, environment variables, API keys, or credential-directory information.

    Files: test/syntheticAgentSelector.test.ts and test/syntheticAgentFailover.test.ts (new files)

    Why these files: Selection and retry semantics govern paid subscription use and require deterministic regression coverage.

    Use table-driven tests for priority fallback, round-robin cursor advancement, usage headroom, exact-cap exclusion, stale usage, uncapped operation without Agent Tank, context filtering, per-call exclusions, all-members-exhausted diagnostics, failed-result retries, thrown-error retries, and cancellation/context errors that bypass retry.

    Extend planning, review-context, and summary-miner tests to assert that the selected physical hard limit or batch override is consulted before prompt/batch construction.

  2. propr-dev commented on Aug 30, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using codex agent with gpt-5.6-sol model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: codex
    • Model: gpt-5.6-sol
    • Branch: 1991/gpt-5.6-sol-implement-context-aware-s-20260830-0155-r4q
    • Base Branch: 1990-epic-synthetic-pool-eus
    • Worktree: issue-1991-20260830-0155-gpt-5.6-sol-r4q

    🔍 Track Task Execution

  3. added a commit that references this issue on Aug 30, 2026
  4. added a commit that references this issue on Aug 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions