s-ttp commited on
Commit
afda041
·
verified ·
1 Parent(s): 606f0ef

Deploy AiVa gateway from 17de1a822c96

Browse files
config/context_profiles.yaml CHANGED
@@ -14,6 +14,9 @@ profiles:
14
  # cases (offline re-score of served predictions, measured) gold passage recall 83.2% -> 94.4% for 65.6%
15
  # -> 53.7% tokens saved (k=1: 85.5%, 64.3%). See ADR-0009.
16
  keep_top_k: 2
 
 
 
17
  preserve_numbers: true
18
  target_budget_tokens: 3000
19
  - id: network-alarm-correlation
 
14
  # cases (offline re-score of served predictions, measured) gold passage recall 83.2% -> 94.4% for 65.6%
15
  # -> 53.7% tokens saved (k=1: 85.5%, 64.3%). See ADR-0009.
16
  keep_top_k: 2
17
+ # Heading-aware fusion (ADR-0009, 2026-10-18 amendment), measured on ML & Data's 150 enterprise-rag
18
+ # questions: GCT Group target @2 0.10 -> 0.20, S4's GCT-POL-014 §3 from rank 3 to 1. Not measured elsewhere.
19
+ heading_fusion: true
20
  preserve_numbers: true
21
  target_budget_tokens: 3000
22
  - id: network-alarm-correlation
config/models.yaml CHANGED
@@ -44,9 +44,14 @@ models:
44
  provider_model_id: Qwen/Qwen3-4B-Instruct-2507
45
  adapter: enterprise-cim-lora
46
  revision: cdbee75f17c01a7cc42f958dc650907174af0554
47
- # Qwen3-4B-Instruct-2507 merged with the CIM LoRA (s-ttp/aiva-cim-qwen3-4b-lora@3ea98ffa), bf16 on 1x L4.
48
- weights_repo: s-ttp/aiva-cim-qwen3-4b
49
- weights_revision: 739f46e97fd5d29298371fdbcdc564e0372e5a96
 
 
 
 
 
50
  endpoint_name: enterprise-cim
51
  region: aws-us-east-1
52
  sovereign: false
 
44
  provider_model_id: Qwen/Qwen3-4B-Instruct-2507
45
  adapter: enterprise-cim-lora
46
  revision: cdbee75f17c01a7cc42f958dc650907174af0554
47
+ # Qwen3-4B-Instruct-2507 merged with the CIM v7 LoRA (s-ttp/aiva-cim-qwen3-4b-v7-lora@cfa0a50b, trained on
48
+ # s-ttp/aiva-cim-sft@da9e8a9d), bf16 on 1x L4. Contract v2: it returns the selection, the gateway builds
49
+ # the package (ADR-0018).
50
+ weights_repo: s-ttp/aiva-cim-qwen3-4b-v7
51
+ weights_revision: 16bd341b02869d8059ee967b3c03abedbfa00974
52
+ cim_contract: v2
53
+ # The task categories v7 was trained on (ML & Data); coding and generation bypass the CIM.
54
+ cim_trained_tasks: [qa, rag, agentic, summarization, analysis]
55
  endpoint_name: enterprise-cim
56
  region: aws-us-east-1
57
  sovereign: false
gateway/src/aiva_gateway/catalog/loader.py CHANGED
@@ -179,6 +179,11 @@ def _validate_references(catalog: Catalog) -> None:
179
  errors.append(f"model {model.id}: unknown rate card {model.rate_card_id}")
180
  if model.sovereign and model.external:
181
  errors.append(f"model {model.id}: a sovereign model cannot be external")
 
 
 
 
 
182
  for ref in (catalog.models.frontier_baseline, catalog.models.cim_model):
183
  if ref not in model_ids:
184
  errors.append(f"models.yaml references unknown model {ref}")
 
179
  errors.append(f"model {model.id}: unknown rate card {model.rate_card_id}")
180
  if model.sovereign and model.external:
181
  errors.append(f"model {model.id}: a sovereign model cannot be external")
182
+ errors.extend(
183
+ f"model {model.id}: unknown trained task {t}"
184
+ for t in model.cim_trained_tasks or ()
185
+ if t not in catalog.taxonomy.dimensions.get("task_category", ())
186
+ )
187
  for ref in (catalog.models.frontier_baseline, catalog.models.cim_model):
188
  if ref not in model_ids:
189
  errors.append(f"models.yaml references unknown model {ref}")
gateway/src/aiva_gateway/catalog/models.py CHANGED
@@ -115,11 +115,14 @@ class ModelSpec(_Strict):
115
  # The CIM's reply contract (ADR-0018): v1 returns the package (`upstream_messages`); v2 returns selection
116
  # and facts, and the gateway builds the package. Set by the weights a CIM endpoint serves.
117
  cim_contract: Literal["v1", "v2"] = "v1"
 
 
 
118
 
119
  @model_validator(mode="after")
120
  def _weights_pin(self) -> "ModelSpec":
121
- if self.cim_contract != "v1" and self.role != "cim":
122
- raise ValueError(f"model {self.id}: cim_contract applies to the CIM only")
123
  if (self.weights_repo is None) != (self.weights_revision is None):
124
  raise ValueError(f"model {self.id}: weights_repo and weights_revision are pinned together")
125
  if self.weights_repo is not None and self.provider != "hf-endpoint":
@@ -316,6 +319,9 @@ class ContextProfile(_Strict):
316
  keep_top_k: int = Field(default=0, ge=0)
317
  # For applications that accept no omission: every passage is kept, so the CIM is never called.
318
  keep_all_passages: bool = False
 
 
 
319
 
320
  @model_validator(mode="after")
321
  def _citation_fields_are_required(self) -> "ContextProfile":
 
115
  # The CIM's reply contract (ADR-0018): v1 returns the package (`upstream_messages`); v2 returns selection
116
  # and facts, and the gateway builds the package. Set by the weights a CIM endpoint serves.
117
  cim_contract: Literal["v1", "v2"] = "v1"
118
+ # The task categories the CIM's weights were trained on (taxonomy `task_category` ids); a request of any
119
+ # other category bypasses the CIM, with the full context used. Null: no restriction.
120
+ cim_trained_tasks: list[str] | None = None
121
 
122
  @model_validator(mode="after")
123
  def _weights_pin(self) -> "ModelSpec":
124
+ if (self.cim_contract != "v1" or self.cim_trained_tasks is not None) and self.role != "cim":
125
+ raise ValueError(f"model {self.id}: cim_contract and cim_trained_tasks apply to the CIM only")
126
  if (self.weights_repo is None) != (self.weights_revision is None):
127
  raise ValueError(f"model {self.id}: weights_repo and weights_revision are pinned together")
128
  if self.weights_repo is not None and self.provider != "hf-endpoint":
 
319
  keep_top_k: int = Field(default=0, ge=0)
320
  # For applications that accept no omission: every passage is kept, so the CIM is never called.
321
  keep_all_passages: bool = False
322
+ # Heading-aware fusion for this profile's retrieval (ADR-0009, 2026-10-18 amendment): enabled only where
323
+ # it was measured.
324
+ heading_fusion: bool = False
325
 
326
  @model_validator(mode="after")
327
  def _citation_fields_are_required(self) -> "ContextProfile":
gateway/src/aiva_gateway/config.py CHANGED
@@ -107,17 +107,23 @@ class Settings(BaseSettings):
107
  # The cross-encoder reranker is off by default ("none"); "onnx" enables the pinned bge-reranker-base. On
108
  # the 121 held-out RAG cases it did not improve recall and cost about 1.5 s per request (ADR-0009).
109
  reranker_backend: str = "none"
110
- # Heading-aware fusion: a third ranking over section headings joins BM25 and vector search (ADR-0009,
111
- # 2026-10-18 amendment). Off until it is enabled with the next CIM swap, so S2, S4 and S8 re-record once.
 
112
  retrieval_heading_fusion: bool = False
113
- # RLCD classifier (ADR-0009): "model" loads the pinned ModernBERT (needs the `rlcd` extra and HF_TOKEN);
114
- # "fixture" replays recorded model outputs from `rlcd_fixture_path` (tests); "heuristic" uses no model.
115
  # Endpoint A's output decode rate, for the CIM time-budget bypass (ML & Data's measurement, ADR-0009).
116
  cim_decode_tokens_per_s: float = 70.0
117
  # The same for a v2 CIM (ADR-0018). The 70 tok/s above is n-gram speculation on v1 replies that copy whole
118
- # passages; a v2 reply copies only ids and values, so until v6 is measured on Endpoint A, the L4's
119
- # per-stream rate without speculation (29 tok/s, ML & Data).
120
- cim_v2_decode_tokens_per_s: float = 29.0
 
 
 
 
 
 
 
121
  rlcd_backend: str = "heuristic"
122
  rlcd_fixture_path: Path | None = None
123
  # A local copy of the pinned model directory, e.g. baked into the image; skips the Hub download.
 
107
  # The cross-encoder reranker is off by default ("none"); "onnx" enables the pinned bge-reranker-base. On
108
  # the 121 held-out RAG cases it did not improve recall and cost about 1.5 s per request (ADR-0009).
109
  reranker_backend: str = "none"
110
+ # Heading-aware fusion for every request: a third ranking over section headings joins BM25 and vector
111
+ # search (ADR-0009, 2026-10-18 amendment). Off: it is enabled per context profile, where it was measured
112
+ # (`ContextProfile.heading_fusion`).
113
  retrieval_heading_fusion: bool = False
 
 
114
  # Endpoint A's output decode rate, for the CIM time-budget bypass (ML & Data's measurement, ADR-0009).
115
  cim_decode_tokens_per_s: float = 70.0
116
  # The same for a v2 CIM (ADR-0018). The 70 tok/s above is n-gram speculation on v1 replies that copy whole
117
+ # passages; a v2 reply copies only ids and values. Measured (provenance `measured`) for v7@16bd341 on
118
+ # Endpoint A's L4 image and args, per-stream p5 41, p50 62 tok/s; the p5, rounded down. Source: ML & Data,
119
+ # 2026-10-18, ml/reports/endpoint-cim-v2-enterprise-cim-v7-bench.md.
120
+ cim_v2_decode_tokens_per_s: float = 40.0
121
+ # Runaway guard for a v2 CIM (ADR-0018): each call's guided-decoding schema narrows both id lists to the
122
+ # ids sent (`enum`, `maxItems`). On Endpoint A's L4 bench (ML & Data, 2026-10-18) vLLM honours both, the
123
+ # two invented-id loops stop, and 30 of 30 replies that did not loop are byte-identical.
124
+ cim_v2_constrain_ids: bool = True
125
+ # RLCD classifier (ADR-0009): "model" loads the pinned ModernBERT (needs the `rlcd` extra and HF_TOKEN);
126
+ # "fixture" replays recorded model outputs from `rlcd_fixture_path` (tests); "heuristic" uses no model.
127
  rlcd_backend: str = "heuristic"
128
  rlcd_fixture_path: Path | None = None
129
  # A local copy of the pinned model directory, e.g. baked into the image; skips the Hub download.
gateway/src/aiva_gateway/inference/openai_compatible.py CHANGED
@@ -109,6 +109,8 @@ class OpenAICompatibleAdapter(LiveAdapter):
109
  "stream_options": {"include_usage": True},
110
  **self.extra_params,
111
  }
 
 
112
  stream = await client.chat.completions.create(**params)
113
  async for chunk in stream:
114
  if not verified:
 
109
  "stream_options": {"include_usage": True},
110
  **self.extra_params,
111
  }
112
+ if request.response_format is not None:
113
+ params["response_format"] = request.response_format
114
  stream = await client.chat.completions.create(**params)
115
  async for chunk in stream:
116
  if not verified:
gateway/src/aiva_gateway/optimize/cim_live.py CHANGED
@@ -19,7 +19,7 @@ falls back to the full eligible context. A truncated reply (`CIM_TRUNCATED`) is
19
 
20
  import json
21
  import time
22
- from collections.abc import Sequence
23
  from typing import Any, Literal
24
 
25
  from pydantic import ValidationError
@@ -51,11 +51,12 @@ CIM_CONTEXT_EXCEEDED = "CIM_CONTEXT_EXCEEDED"
51
  CIM_DECODE_TOKENS_PER_S = 70.0
52
  CIM_TIME_BUDGET_SHARE = 0.8
53
  # A v2 reply's structure and one `{field, value, source_id}` entry in context, in real tokens (ML & Data, gold
54
- # v2 targets of the v6 dataset, 29,203 entries: per-row mean 26.5, p95 33.1, max 38.9; v6's measured output
55
- # confirms it before the swap).
56
  SELECTION_OVERHEAD_TOKENS = 128
57
  FACT_ENTRY_TOKENS = 40
58
  NOTHING_TO_OMIT = "nothing-to-omit"
 
59
  TOO_LARGE_TO_BUILD_IN_TIME = "too-large-to-build-in-time"
60
 
61
  CIM_SYSTEM_PROMPT = f"""You are a context intelligence model. You receive a JSON request with a task, the \
@@ -113,7 +114,7 @@ def _schema_v2() -> dict[str, Any]:
113
 
114
 
115
  RESPONSE_SCHEMA_V2 = _schema_v2()
116
- RESPONSE_FORMAT_V2 = {
117
  "type": "json_schema",
118
  "json_schema": {"name": "cim_response", "schema": RESPONSE_SCHEMA_V2, "strict": True},
119
  }
@@ -121,6 +122,22 @@ CIM_EXTRA_PARAMS_V2: dict[str, object] = {"temperature": 0, "response_format": R
121
  CIM_EXTRA_PARAMS_BY_CONTRACT = {"v1": CIM_EXTRA_PARAMS, "v2": CIM_EXTRA_PARAMS_V2}
122
 
123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  class CimSelection(ContractModel):
125
  """A v2 reply: every `CimResponse` field but the package, all required (`RESPONSE_SCHEMA_V2`)."""
126
 
@@ -176,6 +193,15 @@ def cim_max_output_tokens(
176
  return min(reply, context_window - prompt)
177
 
178
 
 
 
 
 
 
 
 
 
 
179
  def package_build_seconds(
180
  kept: Sequence[CimEvidence], messages: Sequence[dict[str, str]], decode_tokens_per_s: float
181
  ) -> float:
@@ -208,13 +234,19 @@ def cim_bypass_reason(
208
  decode_tokens_per_s: float = CIM_DECODE_TOKENS_PER_S,
209
  floor: Sequence[CimEvidence] = (),
210
  contract: CimContract = "v1",
 
 
211
  ) -> str | None:
212
  """Why a CIM call cannot help, or None to call it. Derived from the Context Guard (`passages_to_keep`)
213
  and the recall floor (`floor`, passages the gateway keeps whatever the CIM selects):
 
214
  - every passage must be kept, so the only verifiable package is the full context; or
215
  - the reply could not be emitted within the CIM's time budget: under v1 the package of the passages that
216
  must be kept, under v2 the selection with every required fact the evidence holds.
217
  """
 
 
 
218
  if not evidence:
219
  return None
220
  required = {e.id for e in passages_to_keep(evidence, messages, profile)} | {e.id for e in floor}
@@ -256,11 +288,15 @@ def parse_cim_response(
256
 
257
  class LiveContextIntelligence:
258
  """Wraps an OpenAI-compatible adapter configured with the contract's extra params
259
- (`CIM_EXTRA_PARAMS_BY_CONTRACT`)."""
 
260
 
261
- def __init__(self, adapter: InferenceAdapter, contract: CimContract = "v1") -> None:
 
 
262
  self._adapter = adapter
263
  self.contract: CimContract = contract
 
264
 
265
  async def aclose(self) -> None:
266
  close = getattr(self._adapter, "aclose", None)
@@ -270,7 +306,7 @@ class LiveContextIntelligence:
270
  async def package(self, request: CimRequest, model: ModelSpec) -> CimCallResult:
271
  started = time.perf_counter()
272
  max_output_tokens = cim_max_output_tokens(request, model.context_window, self.contract)
273
- if max_output_tokens < MIN_CIM_OUTPUT_TOKENS:
274
  # The prompt leaves no room for a package in the endpoint's context: not called, nothing billed.
275
  provenance = getattr(self._adapter, "provenance", Provenance.MEASURED)
276
  return CimCallResult(
@@ -289,6 +325,7 @@ class LiveContextIntelligence:
289
  messages=cim_messages(request, self.contract),
290
  max_output_tokens=max_output_tokens,
291
  timeout_seconds=CIM_TIMEOUT_SECONDS,
 
292
  )
293
  )
294
  # The pinned weights the resolver confirmed (`<repo>@<revision[:12]>`), else what the server reported.
 
19
 
20
  import json
21
  import time
22
+ from collections.abc import Collection, Sequence
23
  from typing import Any, Literal
24
 
25
  from pydantic import ValidationError
 
51
  CIM_DECODE_TOKENS_PER_S = 70.0
52
  CIM_TIME_BUDGET_SHARE = 0.8
53
  # A v2 reply's structure and one `{field, value, source_id}` entry in context, in real tokens (ML & Data, gold
54
+ # v2 targets of the v6 dataset, 29,203 entries: per-row mean 26.5, p95 33.1, max 38.9; v7 measured on Endpoint
55
+ # A's L4 bench, 2026-10-18: mean 26.5, p95 30.4, max 33.2).
56
  SELECTION_OVERHEAD_TOKENS = 128
57
  FACT_ENTRY_TOKENS = 40
58
  NOTHING_TO_OMIT = "nothing-to-omit"
59
+ TASK_OUTSIDE_TRAINING = "task-outside-cim-training"
60
  TOO_LARGE_TO_BUILD_IN_TIME = "too-large-to-build-in-time"
61
 
62
  CIM_SYSTEM_PROMPT = f"""You are a context intelligence model. You receive a JSON request with a task, the \
 
114
 
115
 
116
  RESPONSE_SCHEMA_V2 = _schema_v2()
117
+ RESPONSE_FORMAT_V2: dict[str, Any] = {
118
  "type": "json_schema",
119
  "json_schema": {"name": "cim_response", "schema": RESPONSE_SCHEMA_V2, "strict": True},
120
  }
 
122
  CIM_EXTRA_PARAMS_BY_CONTRACT = {"v1": CIM_EXTRA_PARAMS, "v2": CIM_EXTRA_PARAMS_V2}
123
 
124
 
125
+ def constrained_response_format(request: CimRequest) -> dict[str, Any]:
126
+ """Runaway guard (ADR-0018): `RESPONSE_FORMAT_V2` with both id lists narrowed to the ids sent (`enum`)
127
+ and at most one entry per passage (`maxItems`), so guided decoding cannot invent ids past the end of a
128
+ long list. A derived copy that only adds constraints; the pinned schema is unchanged. No evidence: as
129
+ pinned."""
130
+ ids = [e.id for e in request.evidence]
131
+ if not ids:
132
+ return RESPONSE_FORMAT_V2
133
+ properties = dict(RESPONSE_SCHEMA_V2["properties"])
134
+ for key in ("selected_evidence_ids", "omitted_evidence_ids"):
135
+ pinned = properties[key]
136
+ properties[key] = {**pinned, "items": {**pinned["items"], "enum": ids}, "maxItems": len(ids)}
137
+ schema = {**RESPONSE_SCHEMA_V2, "properties": properties}
138
+ return {**RESPONSE_FORMAT_V2, "json_schema": {**RESPONSE_FORMAT_V2["json_schema"], "schema": schema}}
139
+
140
+
141
  class CimSelection(ContractModel):
142
  """A v2 reply: every `CimResponse` field but the package, all required (`RESPONSE_SCHEMA_V2`)."""
143
 
 
193
  return min(reply, context_window - prompt)
194
 
195
 
196
+ def min_cim_output_tokens(request: CimRequest, contract: CimContract = "v1") -> int:
197
+ """Below this reply cap the CIM is not called (`CIM_CONTEXT_EXCEEDED`). v1: `MIN_CIM_OUTPUT_TOKENS`, room
198
+ for a useful package. v2: the same, or the whole selection bound when that is smaller (a few passages),
199
+ so a small v2 request is not refused for asking for less than a package."""
200
+ if contract == "v1":
201
+ return MIN_CIM_OUTPUT_TOKENS
202
+ return min(MIN_CIM_OUTPUT_TOKENS, selection_max_tokens(request))
203
+
204
+
205
  def package_build_seconds(
206
  kept: Sequence[CimEvidence], messages: Sequence[dict[str, str]], decode_tokens_per_s: float
207
  ) -> float:
 
234
  decode_tokens_per_s: float = CIM_DECODE_TOKENS_PER_S,
235
  floor: Sequence[CimEvidence] = (),
236
  contract: CimContract = "v1",
237
+ task: str | None = None,
238
+ trained_tasks: Collection[str] | None = None,
239
  ) -> str | None:
240
  """Why a CIM call cannot help, or None to call it. Derived from the Context Guard (`passages_to_keep`)
241
  and the recall floor (`floor`, passages the gateway keeps whatever the CIM selects):
242
+ - the request's task category is not one the CIM's weights were trained on (`trained_tasks`);
243
  - every passage must be kept, so the only verifiable package is the full context; or
244
  - the reply could not be emitted within the CIM's time budget: under v1 the package of the passages that
245
  must be kept, under v2 the selection with every required fact the evidence holds.
246
  """
247
+ if trained_tasks is not None and task not in trained_tasks:
248
+ # Out of distribution for the CIM's weights, with or without evidence: its reply would be unreliable.
249
+ return TASK_OUTSIDE_TRAINING
250
  if not evidence:
251
  return None
252
  required = {e.id for e in passages_to_keep(evidence, messages, profile)} | {e.id for e in floor}
 
288
 
289
  class LiveContextIntelligence:
290
  """Wraps an OpenAI-compatible adapter configured with the contract's extra params
291
+ (`CIM_EXTRA_PARAMS_BY_CONTRACT`); under v2 with `constrain_ids`, each call's format is narrowed to the ids
292
+ it sends (`constrained_response_format`)."""
293
 
294
+ def __init__(
295
+ self, adapter: InferenceAdapter, contract: CimContract = "v1", *, constrain_ids: bool = False
296
+ ) -> None:
297
  self._adapter = adapter
298
  self.contract: CimContract = contract
299
+ self.constrain_ids = constrain_ids and contract == "v2"
300
 
301
  async def aclose(self) -> None:
302
  close = getattr(self._adapter, "aclose", None)
 
306
  async def package(self, request: CimRequest, model: ModelSpec) -> CimCallResult:
307
  started = time.perf_counter()
308
  max_output_tokens = cim_max_output_tokens(request, model.context_window, self.contract)
309
+ if max_output_tokens < min_cim_output_tokens(request, self.contract):
310
  # The prompt leaves no room for a package in the endpoint's context: not called, nothing billed.
311
  provenance = getattr(self._adapter, "provenance", Provenance.MEASURED)
312
  return CimCallResult(
 
325
  messages=cim_messages(request, self.contract),
326
  max_output_tokens=max_output_tokens,
327
  timeout_seconds=CIM_TIMEOUT_SECONDS,
328
+ response_format=constrained_response_format(request) if self.constrain_ids else None,
329
  )
330
  )
331
  # The pinned weights the resolver confirmed (`<repo>@<revision[:12]>`), else what the server reported.
gateway/src/aiva_gateway/optimize/factory.py CHANGED
@@ -1,5 +1,7 @@
1
  """Build the Optimize stage implementations from settings (wired in services.py)."""
2
 
 
 
3
  from redis.asyncio import Redis
4
  from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
5
 
@@ -41,6 +43,7 @@ def build_retriever(
41
  embedder: Embedder | None,
42
  *,
43
  injection_detector: str,
 
44
  ) -> Retriever:
45
  if not settings.retrieval_enabled or embedder is None:
46
  return NullRetriever()
@@ -51,6 +54,7 @@ def build_retriever(
51
  reranker=reranker,
52
  injection_detector=injection_detector,
53
  heading_fusion=settings.retrieval_heading_fusion,
 
54
  )
55
 
56
 
@@ -63,7 +67,9 @@ def build_context_intelligence(
63
  return SimulatedContextIntelligence(catalog.context_profile)
64
  extra = CIM_EXTRA_PARAMS_BY_CONTRACT[model.cim_contract]
65
  return LiveContextIntelligence(
66
- build_openai_compatible(model, settings, resolver, extra_params=extra), model.cim_contract
 
 
67
  )
68
 
69
 
 
1
  """Build the Optimize stage implementations from settings (wired in services.py)."""
2
 
3
+ from collections.abc import Collection
4
+
5
  from redis.asyncio import Redis
6
  from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
7
 
 
43
  embedder: Embedder | None,
44
  *,
45
  injection_detector: str,
46
+ heading_fusion_profiles: Collection[str] = (),
47
  ) -> Retriever:
48
  if not settings.retrieval_enabled or embedder is None:
49
  return NullRetriever()
 
54
  reranker=reranker,
55
  injection_detector=injection_detector,
56
  heading_fusion=settings.retrieval_heading_fusion,
57
+ heading_fusion_profiles=heading_fusion_profiles,
58
  )
59
 
60
 
 
67
  return SimulatedContextIntelligence(catalog.context_profile)
68
  extra = CIM_EXTRA_PARAMS_BY_CONTRACT[model.cim_contract]
69
  return LiveContextIntelligence(
70
+ build_openai_compatible(model, settings, resolver, extra_params=extra),
71
+ model.cim_contract,
72
+ constrain_ids=settings.cim_v2_constrain_ids,
73
  )
74
 
75
 
gateway/src/aiva_gateway/optimize/retrieval.py CHANGED
@@ -17,6 +17,7 @@ import asyncio
17
  import math
18
  import time
19
  from collections import Counter
 
20
  from dataclasses import dataclass, field, replace
21
  from datetime import UTC, date, datetime
22
 
@@ -130,7 +131,7 @@ class _TenantIndex:
130
  bm25: Bm25Index
131
  by_id: dict[str, int]
132
  screened_out: bool # any chunk held back by prompt-injection screening
133
- headings: Bm25Index | None = None
134
 
135
 
136
  class HybridRetriever:
@@ -144,14 +145,17 @@ class HybridRetriever:
144
  candidates: int = 16,
145
  version_ttl_seconds: float = 30.0,
146
  heading_fusion: bool = False,
 
147
  ) -> None:
148
  self._sessionmaker = sessionmaker
149
  self.embedder = embedder
150
  self.reranker = reranker
151
  self.injection_detector = injection_detector # the running detector's version
152
  self.candidates = candidates
153
- # A third ranking over section headings alone (ADR-0009, 2026-10-18 amendment); off by default.
 
154
  self.heading_fusion = heading_fusion
 
155
  self._version_ttl = version_ttl_seconds
156
  self._versions: dict[str, tuple[float, str]] = {}
157
  self._indexes: dict[str, _TenantIndex] = {}
@@ -173,8 +177,11 @@ class HybridRetriever:
173
  )
174
  documents = [list(row) for row in rows]
175
  key: dict[str, object] = {"docs": documents, "embedder": self.embedder.model_id}
 
176
  if self.heading_fusion:
177
- key["ranking"] = "heading-fusion" # answers retrieved under another ranking are cached apart
 
 
178
  version = f"kb-{sha256_hex(key)[:16]}"
179
  self._versions[tenant_id] = (time.monotonic(), version)
180
  return version
@@ -217,11 +224,7 @@ class HybridRetriever:
217
  bm25=Bm25Index(chunks),
218
  by_id={c.evidence_id: i for i, c in enumerate(chunks)},
219
  screened_out=not all(c.injection_clean for c in chunks),
220
- headings=(
221
- Bm25Index([replace(c, text=section_heading(c.text)) for c in chunks])
222
- if self.heading_fusion
223
- else None
224
- ),
225
  )
226
  self._indexes[tenant_id] = index
227
  return index
@@ -263,7 +266,7 @@ class HybridRetriever:
263
  tenant_id, query, [chunks[i].evidence_id for i in eligible], self.candidates
264
  )
265
  rankings = [lexical, semantic]
266
- if index.headings is not None:
267
  rankings.append(
268
  [chunks[i].evidence_id for i in index.headings.search(query, eligible, self.candidates)]
269
  )
 
17
  import math
18
  import time
19
  from collections import Counter
20
+ from collections.abc import Collection
21
  from dataclasses import dataclass, field, replace
22
  from datetime import UTC, date, datetime
23
 
 
131
  bm25: Bm25Index
132
  by_id: dict[str, int]
133
  screened_out: bool # any chunk held back by prompt-injection screening
134
+ headings: Bm25Index # each chunk's section heading alone, for heading-aware fusion
135
 
136
 
137
  class HybridRetriever:
 
145
  candidates: int = 16,
146
  version_ttl_seconds: float = 30.0,
147
  heading_fusion: bool = False,
148
+ heading_fusion_profiles: Collection[str] = (),
149
  ) -> None:
150
  self._sessionmaker = sessionmaker
151
  self.embedder = embedder
152
  self.reranker = reranker
153
  self.injection_detector = injection_detector # the running detector's version
154
  self.candidates = candidates
155
+ # A third ranking over section headings alone (ADR-0009, 2026-10-18 amendment): for every request, or
156
+ # for the context profiles that opt in (`ContextProfile.heading_fusion`, from the catalog).
157
  self.heading_fusion = heading_fusion
158
+ self.heading_fusion_profiles = frozenset(heading_fusion_profiles)
159
  self._version_ttl = version_ttl_seconds
160
  self._versions: dict[str, tuple[float, str]] = {}
161
  self._indexes: dict[str, _TenantIndex] = {}
 
177
  )
178
  documents = [list(row) for row in rows]
179
  key: dict[str, object] = {"docs": documents, "embedder": self.embedder.model_id}
180
+ # Answers retrieved under another ranking are cached apart.
181
  if self.heading_fusion:
182
+ key["ranking"] = "heading-fusion"
183
+ elif self.heading_fusion_profiles:
184
+ key["heading_fusion_profiles"] = sorted(self.heading_fusion_profiles)
185
  version = f"kb-{sha256_hex(key)[:16]}"
186
  self._versions[tenant_id] = (time.monotonic(), version)
187
  return version
 
224
  bm25=Bm25Index(chunks),
225
  by_id={c.evidence_id: i for i, c in enumerate(chunks)},
226
  screened_out=not all(c.injection_clean for c in chunks),
227
+ headings=Bm25Index([replace(c, text=section_heading(c.text)) for c in chunks]),
 
 
 
 
228
  )
229
  self._indexes[tenant_id] = index
230
  return index
 
266
  tenant_id, query, [chunks[i].evidence_id for i in eligible], self.candidates
267
  )
268
  rankings = [lexical, semantic]
269
+ if self.heading_fusion or (profile is not None and profile.id in self.heading_fusion_profiles):
270
  rankings.append(
271
  [chunks[i].evidence_id for i in index.headings.search(query, eligible, self.candidates)]
272
  )
gateway/src/aiva_gateway/pipeline/interfaces.py CHANGED
@@ -3,7 +3,7 @@
3
  from collections.abc import Mapping
4
  from dataclasses import dataclass, field
5
  from datetime import datetime
6
- from typing import Protocol
7
 
8
  from aiva_gateway.catalog.models import ContextProfile, ModelSpec
9
  from aiva_gateway.contracts.cim import CimEvidence, CimRequest, CimResponse
@@ -343,6 +343,8 @@ class InferenceRequest:
343
  timeout_seconds: float = 120.0
344
  # Reasoning effort where the provider takes one (Anthropic); None = the adapter's configured effort.
345
  effort: str | None = None
 
 
346
 
347
 
348
  @dataclass(frozen=True)
 
3
  from collections.abc import Mapping
4
  from dataclasses import dataclass, field
5
  from datetime import datetime
6
+ from typing import Any, Protocol
7
 
8
  from aiva_gateway.catalog.models import ContextProfile, ModelSpec
9
  from aiva_gateway.contracts.cim import CimEvidence, CimRequest, CimResponse
 
343
  timeout_seconds: float = 120.0
344
  # Reasoning effort where the provider takes one (Anthropic); None = the adapter's configured effort.
345
  effort: str | None = None
346
+ # Structured output for this call (OpenAI-compatible adapters); None = the adapter's configured format.
347
+ response_format: dict[str, Any] | None = None
348
 
349
 
350
  @dataclass(frozen=True)
gateway/src/aiva_gateway/pipeline/orchestrator.py CHANGED
@@ -61,7 +61,12 @@ from aiva_gateway.inference.registry import AdapterRegistry
61
  from aiva_gateway.inference.tokens import bound_for_estimate, input_token_bound
62
  from aiva_gateway.optimize.cache import build_cache_key
63
  from aiva_gateway.optimize.cim import EVIDENCE_PREAMBLE, evidence_block, with_passages
64
- from aiva_gateway.optimize.cim_live import NOTHING_TO_OMIT, TOO_LARGE_TO_BUILD_IN_TIME, cim_bypass_reason
 
 
 
 
 
65
  from aiva_gateway.optimize.context_guard import BUDGET_TOLERANCE
66
  from aiva_gateway.pipeline.context import AttemptRecord, BudgetApprovalRecord, PolicyEventRecord, RunContext
67
  from aiva_gateway.pipeline.interfaces import (
@@ -93,6 +98,7 @@ CIM_BYPASS_MESSAGES = {
93
  NOTHING_TO_OMIT: "CIM bypassed: nothing to omit; full context used",
94
  TOO_LARGE_TO_BUILD_IN_TIME: "CIM bypassed: package too large to build in time; full context used",
95
  ENDPOINT_COLD: "CIM bypassed: the CIM endpoint is asleep and is not woken; full context used",
 
96
  }
97
  CACHE_HIT_MESSAGE = "Full response-cache hit: no upstream inference call"
98
  UPSTREAM_ATTEMPTS = 2 # initial call plus one bounded retry, all reserved up front
@@ -499,6 +505,8 @@ class Orchestrator:
499
  ),
500
  floor=floor,
501
  contract=contract,
 
 
502
  )
503
  if bypass is None and cim_spec is not None and not await self._awake(ctx, cim_spec):
504
  bypass = ENDPOINT_COLD
 
61
  from aiva_gateway.inference.tokens import bound_for_estimate, input_token_bound
62
  from aiva_gateway.optimize.cache import build_cache_key
63
  from aiva_gateway.optimize.cim import EVIDENCE_PREAMBLE, evidence_block, with_passages
64
+ from aiva_gateway.optimize.cim_live import (
65
+ NOTHING_TO_OMIT,
66
+ TASK_OUTSIDE_TRAINING,
67
+ TOO_LARGE_TO_BUILD_IN_TIME,
68
+ cim_bypass_reason,
69
+ )
70
  from aiva_gateway.optimize.context_guard import BUDGET_TOLERANCE
71
  from aiva_gateway.pipeline.context import AttemptRecord, BudgetApprovalRecord, PolicyEventRecord, RunContext
72
  from aiva_gateway.pipeline.interfaces import (
 
98
  NOTHING_TO_OMIT: "CIM bypassed: nothing to omit; full context used",
99
  TOO_LARGE_TO_BUILD_IN_TIME: "CIM bypassed: package too large to build in time; full context used",
100
  ENDPOINT_COLD: "CIM bypassed: the CIM endpoint is asleep and is not woken; full context used",
101
+ TASK_OUTSIDE_TRAINING: "CIM bypassed: task outside the CIM's trained categories; full context used",
102
  }
103
  CACHE_HIT_MESSAGE = "Full response-cache hit: no upstream inference call"
104
  UPSTREAM_ATTEMPTS = 2 # initial call plus one bounded retry, all reserved up front
 
505
  ),
506
  floor=floor,
507
  contract=contract,
508
+ task=ctx.assessment.task_category if ctx.assessment else None,
509
+ trained_tasks=cim_spec.cim_trained_tasks if cim_spec else None,
510
  )
511
  if bypass is None and cim_spec is not None and not await self._awake(ctx, cim_spec):
512
  bypass = ENDPOINT_COLD
gateway/src/aiva_gateway/services.py CHANGED
@@ -142,7 +142,11 @@ def build_services(settings: Settings, **overrides: Any) -> Services:
142
  "rlcd": rlcd,
143
  # Knowledge-base chunks count as screened only by the detector this scanner runs (ADR-0011).
144
  "retriever": build_retriever(
145
- settings, sessionmaker, embedder, injection_detector=dlp.injection.version
 
 
 
 
146
  ),
147
  "cim": cim,
148
  "context_guard": DeterministicContextGuard(),
 
142
  "rlcd": rlcd,
143
  # Knowledge-base chunks count as screened only by the detector this scanner runs (ADR-0011).
144
  "retriever": build_retriever(
145
+ settings,
146
+ sessionmaker,
147
+ embedder,
148
+ injection_detector=dlp.injection.version,
149
+ heading_fusion_profiles=[p.id for p in catalog.context_profiles if p.heading_fusion],
150
  ),
151
  "cim": cim,
152
  "context_guard": DeterministicContextGuard(),