Document abstract
This document specifies the complete architecture of AutonomIQ Deal Desk, a GCP-native event-driven agentic system that processes inbound Salesforce opportunity events without human intervention below a configurable deal-value threshold. The pipeline autonomously retrieves CRM context, queries ERP pricing, executes Retrieval-Augmented Generation over a redacted corpus of historical contract precedents hosted in AlloyDB pgvector, computes gross margin via a deterministic BigQuery rule engine, synthesises a compliant quote document via Gemini 1.5 Pro, conditionally routes above-threshold deals for human approval, and writes all artefacts back to Salesforce — within a target end-to-end latency of under 90 seconds for straight-through deals.
The architecture is partitioned into four layers: a collapsed event-and-notification surface (Presentation & Experience), a Vertex AI Agent SDK-based orchestration tier (Agent Orchestration), a Gemini + RAG intelligence tier (MLOps & Intelligence), and a hardened GCP infrastructure tier. Nine Architecture Decision Records document material design choices with full rationale, considered alternatives, and explicit rebuttals to the strongest counterarguments.
Motivation and problem domain
Enterprise deal desks operate at the intersection of revenue velocity and commercial compliance. The canonical workflow involves six to nine discrete information-gathering steps: CRM opportunity retrieval, pricing-tier lookup, inventory check, contract-precedent review, margin computation, quote document generation, compliance flag resolution, and approval routing. In manually operated environments this requires coordination across three to five systems and two to four human participants, yielding a median cycle time of 4–24 hours per deal.[1]
For high-volume, low-to-mid-value deals — commonly 60–75% of enterprise pipeline by count but only 20–35% by value — the human cost is disproportionate to the revenue at risk. The opportunity cost of cycle-time delay compounds this inefficiency.[2]
Existing CPQ tools, including Salesforce Revenue Cloud and Einstein CPQ, address within-CRM configuration and pricing but do not provide autonomous end-to-end orchestration across external systems, unstructured contract-precedent retrieval via RAG, or contextual reasoning over multi-variable margin rules. The gap is specifically in agentic orchestration: the capacity to plan, execute, evaluate, and revise a multi-step workflow without human initiation of each step.
Architectural constraints and non-goals
| Constraint | Category | Implication |
|---|---|---|
| All computation below threshold must be non-interactive | Functional | No UI rendering, no human polling; all state must be durably held between async steps. |
| Every quote field must be traceable to source data | Compliance | Each line item carries a provenance pointer: source system, record ID, retrieval timestamp. |
| Salesforce is the authoritative system of record | Integration | All writes must be idempotent relative to Opportunity ID. No shadow record creation. |
| No PII in the vector store | Privacy/GDPR | Contract corpus must be DLP-redacted before embedding. Named entities stripped to category tokens. |
| Approval threshold is operator-configurable without redeployment | Operational | Threshold persisted in Cloud Firestore; updated by ops team at runtime. |
| Agent must be idempotent on duplicate events | Reliability | Pub/Sub at-least-once delivery requires deduplication at the orchestrator entry point. |
| GCP-only compute; Salesforce is external SaaS | Platform | No on-premise dependencies. SF connectivity via REST/Bulk API v2 over mTLS. |
Non-goals
The following are explicitly out of scope: multi-currency conversion engine; contract clause negotiation; customer-facing quote portal; real-time inventory reservation; post-close revenue recognition; procurement system integration downstream of the quote.
C4 Level 1 — System context
The C4 L1 diagram establishes the system boundary of AutonomIQ and its external actor relationships. Two human roles interact at defined exception points only; all other interactions are system-to-system.
3.1 — C4 Level 2: Container diagram
The container diagram decomposes AutonomIQ into its deployable units, showing inter-container communication protocols and data flows.
L1 Presentation & Experience Layer
The L1 layer comprises three surface types: the Salesforce record surface (primary human-readable output written back by the SF Connector), the approval notification surface (Slack Block Kit messages and Salesforce Approval Tasks from the Approval Router), and the ops observability surface (Cloud Monitoring dashboards consumed by the platform team).
4.1 — Salesforce quote record schema
| Field | Type | Source | Notes |
|---|---|---|---|
QuoteNumber__c | String | Orchestrator | UUID derived from OpportunityId + timestamp. Idempotency key. |
TotalDealValue__c | Currency | Margin Engine | Sum of line items at agreed unit price. |
GrossMarginPct__c | Percent | Margin Engine | (Revenue - COGS) / Revenue. Provenance pointer to BQ audit row. |
PrecedentDealIds__c | Text | Intelligence Svc | Comma-delimited IDs of top-3 RAG-retrieved contract precedents. |
AgentRunId__c | String | Orchestrator | Cloud Workflows execution ID. Links to full audit trail. |
ApprovalStatus__c | Picklist | Approval Router | PENDING_REVIEW / AWAITING_APPROVAL / APPROVED / REJECTED. |
QuotePDFUrl__c | URL | Quote Generator | Signed GCS URL (72h expiry) to rendered PDF artefact. |
L2 Agent Orchestration Layer
The orchestration layer is the central nervous system of AutonomIQ. It implements a ReAct (Reason + Act) loop using the Vertex AI Agent SDK, constrained to a maximum of 12 reasoning turns per execution. The orchestrator receives a normalised event from Pub/Sub, constructs an initial agent context, and iteratively calls registered tools until a terminal state is reached.
5.1 — Tool manifest and SLA contracts
| Tool Name | Owner Service | Protocol | Timeout | Retry Policy |
|---|---|---|---|---|
get_crm_opportunity | SF Connector | HTTPS REST | 10s | 3× exp backoff, jitter |
get_pricing_rules | ERP Connector | HTTPS REST | 8s | 3× exp backoff |
retrieve_contract_precedents | Intelligence Svc | gRPC | 15s | 2× linear, then FAIL |
compute_margin | Margin Engine | HTTPS REST | 12s | 2× exp backoff |
generate_quote_document | Quote Generator | HTTPS REST | 25s | 1× retry, then FAIL |
evaluate_approval_threshold | Approval Router | HTTPS REST | 5s | 3× exp backoff |
post_quote_to_salesforce | SF Connector | HTTPS REST | 15s | 5× exp backoff (idempotent) |
L3 MLOps & Intelligence Layer
The intelligence layer performs three distinct reasoning tasks: contract precedent retrieval via RAG, quote synthesis and compliance reasoning via Gemini 1.5 Pro, and deterministic margin computation via BigQuery. These are explicitly separated to allow independent scaling, observability, and model substitution.
6.1 — Gemini model selection and task routing
| Task | Model | Rationale | Approx tokens |
|---|---|---|---|
| Agent planning / tool selection (ReAct turns) | gemini-1.5-flash-002 | Low latency (<1s), sufficient for structured tool-call decisions over a known 7-tool manifest. | 500–800 / turn |
| Quote document synthesis + compliance reasoning | gemini-1.5-pro-002 | Multi-document reasoning over RAG context + pricing state. Large context window required. | 4,000–12,000 |
| Margin anomaly detection (post-compute) | gemini-1.5-flash-002 | Binary classification over structured JSON. No generation required. | 300–500 |
L4 Infrastructure Layer
All compute is containerised on Cloud Run (fully managed, serverless). No persistent compute VMs are provisioned. Storage is tiered: AlloyDB for vector workloads, BigQuery for analytics and audit, Cloud Firestore for configuration and deduplication state, and Cloud Storage for artefact persistence.
7.1 — Infrastructure sizing baseline
| Service | Spec | Scale policy | Rationale |
|---|---|---|---|
| Cloud Run — Orchestrator | 2 vCPU / 8 GiB, min 1 | Scale to 20 on queue depth | Min-1 eliminates cold-start on the critical path |
| Cloud Run — Intelligence | 4 vCPU / 16 GiB, min 1 | Scale to 10 on CPU | Gemini client requires memory for response streaming; 4-vCPU enables gRPC concurrency |
| AlloyDB Primary | 8 vCPU / 64 GiB, 2 read replicas | Read replica autoscale | HNSW in-memory index for 10M vectors requires ~60 GiB working set |
| BigQuery | 500 slot reservation | Autoscale to 2000 | Reservation prevents slot contention from analytics workloads on the latency-critical margin path |
Happy path: straight-through deal below approval threshold
Above-threshold deal: approval routing path
Agent execution state machine
ADR log — material design decisions
Each ADR follows the Nygard template[3] extended with an explicit Rebuttal field addressing the strongest counterargument to the accepted decision.
- Context
- The orchestration layer requires a ReAct loop with tool-calling, state management, and retry handling. Two options: implement the loop directly in Python against the Gemini API, or use the Vertex AI Agent SDK which provides these primitives.
- Decision
- Use the Vertex AI Agent SDK. It provides managed tool-call dispatch, turn-limit enforcement, structured memory, and built-in Vertex AI tracing — all required capabilities.
- Alternatives
- LangChain/LangGraph (OSS, more portable); custom Python ReAct (maximum control); Vertex AI Reasoning Engine (higher abstraction).
- Consequences
- Coupling to the Vertex AI ecosystem. Migration requires re-implementing the tool manifest and state model. Positive: managed retry, tracing, and quota enforcement reduce implementation surface by ~40%.
- Context
- Contract precedent retrieval requires ANN vector search over ~500K document chunks. Metadata filter requirement (segment, value tier, date recency) and transactional consistency with chunk metadata favour a relational-plus-vector store.
- Decision
- AlloyDB PostgreSQL with the pgvector extension and HNSW indexing. Metadata filters are expressed as SQL WHERE clauses on the same relation as the vector column, eliminating a cross-system join.
- Alternatives
- Vertex AI Vector Search (fully managed, higher QPS); Pinecone (best-in-class ANN); Spanner with vector; BigQuery ML vector search.
- Consequences
- AlloyDB cluster requires HA configuration and backup policy. HNSW index must be rebuilt on major corpus updates. At 10M vectors, HNSW in-memory index requires ~60 GiB RAM on the primary node.
- Context
- Gross margin calculation is a financially material computation involving multi-variable arithmetic over structured data: unit COGS, discount schedules, FX rates, partner tier adjustments. LLMs can produce these computations but are non-deterministic.
- Decision
- Margin computed exclusively via parameterised BigQuery SQL against a versioned pricing rules table. The LLM receives the pre-computed result as grounding context and does not perform arithmetic. BQ row IDs provide full provenance.
- Alternatives
- Gemini with function-calling arithmetic tools; Python Cloud Run service with embedded rules engine; Drools/Open Policy Agent.
- Consequences
- Pricing rule changes require schema migration in BigQuery, not prompt modification. Adds ~800ms to the critical path for BQ slot allocation and query execution.
- Context
- Six pipeline services require isolated compute with independent scaling. The deal volume profile is spiky with long idle periods.
- Decision
- All services on Cloud Run (fully managed). Min-instances set to 1 for latency-critical paths (Orchestrator, SF Connector) and 0 for batch-tolerant paths.
- Alternatives
- GKE Autopilot (more control, Kubernetes API); GKE Standard (full control, full overhead); Cloud Functions (single-purpose, 9MB limit).
- Consequences
- Cloud Run max request timeout is 3600s, sufficient for all services. gRPC streaming is supported on Cloud Run and used for the Intelligence ↔ AlloyDB path.
- Context
- Approval threshold changes on a quarterly cadence and must be modifiable by the Deal Desk ops team without engineering involvement or service redeployment.
- Decision
- Threshold parameters stored as a Firestore document in
deal_desk_configcollection. Approval Router reads with a 60s local TTL cache. Changes take effect within 60 seconds of a Firestore write.
- Alternatives
- Environment variables (requires redeployment); Secret Manager (correct for secrets, not business config); Remote Config (Firebase, appropriate for mobile apps).
- Consequences
- Audit trail of threshold changes maintained via Cloud Audit Logs (all Firestore writes are logged). Previous threshold value preserved in Firestore document history.
- Context
- Salesforce Outbound Messages deliver opportunity events via Apigee to Pub/Sub. The Orchestrator (Cloud Run) must process these events. Two delivery patterns available: push or pull.
- Decision
- Push subscription to the Orchestrator Cloud Run service URL. Push eliminates the polling loop, triggers Cloud Run scale-out directly, and integrates with the min-instance configuration to handle concurrent deal bursts.
- Consequences
- At-least-once delivery requires idempotency at the Orchestrator. Deduplication uses Pub/Sub message ID as Firestore key with 7-day TTL.
- Context
- Two distinct model quality/cost trade-offs: (1) ReAct planning turns — structured JSON tool selection over a known 7-tool manifest (simple classification); (2) Quote synthesis — multi-document reasoning over RAG context, pricing state, and compliance clause generation (complex generation).
- Decision
- Gemini 1.5 Flash for all ReAct planning turns (<800ms, ~600 tokens/turn). Gemini 1.5 Pro for quote synthesis (<20s, up to 12K tokens).
- Consequences
- Two distinct billing dimensions. Model versions must be pinned (e.g.,
gemini-1.5-flash-002) to prevent behaviour drift on model updates.
- Context
- Historical contracts contain PII: customer names, signatory personal details, contact information. Embedding PII into the vector store creates a GDPR-scope data subject rights problem — erasure from a dense vector store is practically infeasible without full re-embedding.
- Decision
- All contracts pass through Cloud DLP before chunking. Named entity recognition identifies PERSON, EMAIL, PHONE, ADDRESS entities and replaces them with category tokens (e.g., [PERSON_1]). Redacted text is embedded; original retained in GCS with restricted IAM.
- Consequences
- DLP redaction adds ~2–5s to offline ingestion pipeline per document (not on critical online path). Category substitution reduces semantic precision for queries targeting specific named parties — acceptable because the use case is structural, not identity-based.
- Context
- Every agent run must produce a durable, queryable audit trail: tools called, inputs, results, model used, decision made. Must support both real-time operational queries and historical analytics (margin distribution, approval rate by segment).
- Decision
- Agent run events written to BigQuery (
deal_desk_audit_events, partitioned by date, clustered by opportunity_id). Cloud Logging receives the same events via Log Sink. BigQuery is the primary analytical surface; Cloud Logging provides real-time operational search.
- Consequences
- BigQuery streaming inserts incur cost (~$0.01/200MB). At target deal volume (<10K/day), streaming insert path is appropriate.
Consolidated rebuttal register — system-level objections
R1 — "This could be built entirely within Salesforce with Einstein CPQ and Flows"
Salesforce Flow and Einstein CPQ address the within-CRM configuration-and-pricing problem well. The design gap is twofold: (1) cross-system orchestration — Flow governor limits (CPU: 10s, heap: 6MB per transaction) make multi-step retrieval from external systems within a single execution context impractical; and (2) unstructured document reasoning — Einstein has no RAG infrastructure over external contract corpora. The RAG requirement alone mandates a vector store and an embedding pipeline, neither of which exist natively in Salesforce. The GCP layer performs specific capabilities that Einstein's architecture cannot provide.
R2 — "Autonomous financial decisions introduce unacceptable risk"
This conflates risk magnitude with risk category. Below-threshold deals (<$75K) represent low-monetary-risk transactions where the cost of a deal-desk error is bounded and recoverable. The system can be deployed at $0 threshold (all deals routed for approval) and the threshold raised incrementally. Three independent safety mechanisms: (1) a margin floor below which any deal is auto-rejected; (2) a maximum ReAct turn limit with forced failure and human DLQ review; (3) a full immutable audit trail enabling post-hoc review. Risk is managed by parameterisation, not architecture removal.
R3 — "LLM-generated quote documents cannot be compliant without human review"
Quote generation is template-constrained generation, not open-ended text generation. The Jinja2 template defines the structural and contractual skeleton; Gemini 1.5 Pro fills only factual fields (product descriptions, deal-specific line items, precedent-derived clause selections from a fixed Legal-approved library). No free-text clause invention occurs. All numeric fields are sourced from deterministic upstream computations, not LLM generation. The quote PDF is attached to a Salesforce record where the sales team reviews before customer delivery. Compliance review targets the template and clause library, not each individual LLM invocation.
Identity, trust boundaries, and data classification
13.1 — Data classification
| Data Element | Classification | Storage | Control |
|---|---|---|---|
| Raw contract PDFs | CONFIDENTIAL | GCS restricted bucket | IAM binding to ingestion SA only; CMEK; VPC-SC |
| Redacted contract embeddings | INTERNAL | AlloyDB | SA binding; PSC endpoint; CMEK |
| Quote JSON + PDF | CONFIDENTIAL | GCS + Salesforce | Signed URLs (72h TTL); SF field-level security |
| Agent audit events | INTERNAL | BigQuery | Column-level security; no external export |
| Salesforce OAuth credentials | SECRET | Secret Manager | CMEK; versioned; 90-day rotation; access audit logged |
Metrics, tracing, and alerting architecture
| Signal Type | Source | Destination | Key Metrics / Use |
|---|---|---|---|
| Agent traces | Vertex AI Agent SDK | Cloud Trace | E2e latency per tool call; ReAct turn count distribution; breakdown by tool |
| Service logs | Cloud Run structured logs | Cloud Logging | Per-service request rate, error rate, latency; opportunity_id for correlation |
| Business metrics | Agent runs (BigQuery writes) | BigQuery → Looker | Quote generation rate; approval rate; margin distribution; STP rate; model token consumption |
| Infrastructure metrics | Cloud Monitoring | Cloud Monitoring | Cloud Run instance count; AlloyDB replication lag; BigQuery slot utilisation; Pub/Sub backlog |
| Alerting | Cloud Monitoring alert policies | PagerDuty / Slack | P0: DLQ non-empty; AlloyDB unreachable. P1: failure rate >5%; p95 latency >120s. P2: approval SLA breach |
14.1 — SLA targets
| SLI | Target | Measurement window |
|---|---|---|
| Straight-through deal completion rate | >99% | Rolling 7 days |
| End-to-end latency p95 (below threshold) | <90s | Rolling 24 hours |
| Agent error rate (unhandled → DLQ) | <1% | Rolling 7 days |
| Quote provenance completeness | 100% | Per audit event |
| Approval notification delivery | <60s from decision | Per event |
Operational evolution, graduation paths, and maintenance model
Day 2 operations encompasses the steady-state posture post-initial deployment, including model maintenance, corpus management, threshold calibration, and the architectural graduation paths triggered by growth or changed requirements.
Monitor ReAct turn distribution. Calibrate approval threshold using actual deal-value and margin distribution data from BigQuery. Run fortnightly contract corpus re-ingestion jobs (new deals added to GCS trigger Cloud Run Job via Eventarc). Review Cloud DLP false-negative rate against redacted output samples.
Model pinning policy: all Gemini model versions are pinned in Vertex AI endpoint configuration. On new model release: (1) run offline evaluation harness against 500-deal golden dataset; (2) shadow-traffic 5% of live deals to new model for 72 hours; (3) compare quote JSON structure and margin-grounding accuracy; (4) promote if both metrics improve or are neutral. Rollback via endpoint version repin — no redeployment required.
When the corpus exceeds 5 million embeddings, AlloyDB HNSW in-memory index requirement (~300 GiB) becomes cost-prohibitive. Migration path: deploy Vertex AI Vector Search index alongside AlloyDB. Run dual-retrieval for 30 days, validating recall@5 parity. Cut over AlloyDB to metadata-only store; all ANN queries route to Vertex AI Vector Search.
At >20 Cloud Run services, the absence of a service mesh becomes an operational burden. Migration path: deploy GKE Autopilot cluster; migrate services incrementally using Cloud Run → GKE tooling; deploy Istio via Cloud Service Mesh for mTLS, circuit breaking, and canary deployment. Cloud Run remains as the external ingress tier.
Current design targets us-central1 single region. DR graduation: AlloyDB read replicas in us-east1; BigQuery multi-region dataset; Cloud Run services to us-east1 behind Global Load Balancer; Pub/Sub regional failover. RTO target: <15 minutes; RPO: <5 minutes via AlloyDB replication.
15.1 — Day 2 operational runbooks
Failed runs are published to deal_desk_dlq Pub/Sub topic. The DLQ subscription delivers to a separate Cloud Run service (dlq-processor) which: (1) writes a structured failure record to BigQuery with full agent state dump; (2) creates a Salesforce Task assigned to the Deal Desk ops team with the failure summary; (3) sends a P0 alert via Cloud Monitoring. The ops team reviews the agent state JSON, identifies the failure cause, and either re-triggers the event via a retry Cloud Function or manually processes the deal in Salesforce.
New contracts are added to deal-desk-contracts-raw GCS bucket. Eventarc triggers a Cloud Run Job which: (1) runs DLP redaction on new files only (incremental, tracked via Firestore metadata); (2) chunks to 768-token windows with 10% overlap; (3) generates embeddings via Vertex AI Embedding API in batches of 250; (4) upserts to AlloyDB using contract_id as deduplication key; (5) writes ingestion metadata to BigQuery. Full re-embedding (required only on embedding model change) runs as a batch Cloud Run Job with 1000-document parallelism.
Quarterly threshold review: the Deal Desk Manager queries the BigQuery audit dataset for the trailing 90-day deal distribution. The recommended query surfaces: approval rate by deal value decile; margin distribution for approved vs. rejected deals; false-positive rate (above-threshold deals subsequently approved without modification). The Manager updates the Firestore config document directly via an internal admin UI. Changes take effect within 60 seconds. The previous threshold value is preserved in Firestore document history for audit.
Architectural risk register
Gemini 1.5 Pro produces structurally valid but factually incorrect quote fields. Mitigated by: template-constrained generation; numeric fields from BQ only; grounding on retrieved documents; Pydantic schema validation before PDF render. Residual risk: clause selection may be semantically inappropriate without detection.
AlloyDB primary failure during active deal processing halts RAG retrieval. Mitigated by: HA cluster with 2 read replicas; automatic failover <30s; agent retry policy handles transient unavailability. Residual risk: failover during a ReAct turn consumes turns; resolution is routing long-running operations through the Cloud Workflows durability layer.
High deal volume causes SF REST API rate limit to be hit, blocking CRM context retrieval. Mitigated by: SF daily API call monitoring via Cloud Monitoring; SF Connector implements exp backoff with jitter; Bulk API v2 for writeback at scale.
A run stuck in AWAITING_APPROVAL could receive a duplicate Pub/Sub redelivery after the dedup key expires. Mitigated by: Firestore dedup TTL set to 7 days; Pub/Sub message acknowledgment on receipt, not on completion. Correct mitigation prevents redelivery from occurring under normal conditions.
If the embedding model is updated, cosine similarity scores between existing corpus and new query embeddings become incomparable. Mitigated by: embedding model version stored per-vector in AlloyDB metadata; query uses same versioned model; version mismatch alert triggers a full re-embedding job.
Slot reservation shared with analytics workloads. A large analytical query could consume reserved slots and delay margin computation. Mitigated by: dedicated slot reservation for deal_desk project separate from analytics project; pricing queries use LIMIT and parameterised inputs, not full table scans.
Bibliography
- [1]Gartner, "Optimize Deal Desk Operations to Accelerate Revenue," Gartner Research Note G00766843, 2023.
- [2]Forrester Research, "The State of B2B Quote-to-Cash Automation," Forrester Wave Q3 2024.
- [3]M. Nygard, "Documenting Architecture Decisions," cognitect.com/blog, 2011.
- [4]Y. Yao, J. Zhao, et al., "ReAct: Synergizing Reasoning and Acting in Language Models," ICLR 2023. arXiv:2210.03629.
- [5]The Open Group, "TOGAF® Standard, 10th Edition," 2022.
- [6]Simon Brown, "The C4 Model for Visualising Software Architecture," c4model.com, 2018.
- [7]Google Cloud, "Vertex AI Agent SDK Documentation," cloud.google.com/vertex-ai/docs/agents, 2025.
- [8]Google Cloud, "AlloyDB for PostgreSQL: pgvector Extension," cloud.google.com/alloydb/docs/pgvector, 2025.
- [9]P. Lewis et al., "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks," NeurIPS 2020. arXiv:2005.11401.
- [10]Google Cloud, "Gemini 1.5 Technical Report," deepmind.google, 2024.
- [11]NIST SP 800-204B, "Attribute-based Access Control for Microservices," 2021.
- [12]Salesforce, "Salesforce REST API Developer Guide," developer.salesforce.com, 2025.