amfs-http-server 0.3.66__tar.gz → 0.3.68__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: amfs-http-server
3
- Version: 0.3.66
3
+ Version: 0.3.68
4
4
  Summary: AMFS HTTP/REST API server with SSE support
5
5
  License-Expression: Apache-2.0
6
6
  Requires-Python: >=3.11
7
- Requires-Dist: amfs-core>=0.3.55
7
+ Requires-Dist: amfs-core>=0.3.57
8
8
  Requires-Dist: amfs>=0.5.42
9
9
  Requires-Dist: fastapi>=0.115
10
10
  Requires-Dist: httpx>=0.27
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "amfs-http-server"
3
- version = "0.3.66"
3
+ version = "0.3.68"
4
4
  description = "AMFS HTTP/REST API server with SSE support"
5
5
  requires-python = ">=3.11"
6
6
  license = "Apache-2.0"
@@ -27,7 +27,7 @@ dependencies = [
27
27
  # unexpected keyword, _scope_block swallows it, and the block disappears —
28
28
  # while an adapter that ignored the argument instead would name another
29
29
  # agent's private keys. Either way the floor is what makes the rule real.
30
- "amfs-core>=0.3.55",
30
+ "amfs-core>=0.3.57",
31
31
  "fastapi>=0.115",
32
32
  # 0.37 is where uvicorn.run() grew timeout_worker_healthcheck, which
33
33
  # main() passes unconditionally; on anything older that is a TypeError
@@ -173,6 +173,24 @@ class RetrieveRequest(BaseModel):
173
173
  #: a memory the record has confirmed does not need nine alternatives beside
174
174
  #: it in the prompt. Opt-in.
175
175
  adaptive_k: bool = False
176
+ #: Rank the head of the results with the cross-encoder where one is
177
+ #: installed (the default, and what every caller got before this field
178
+ #: existed). Set to False to skip it: the cross-encoder is the slowest
179
+ #: stage of a read, and a caller that reads on every turn of a
180
+ #: conversation can prefer the blended score as it stands. The
181
+ #: ``X-AMFS-Reranked`` response header says whether it ran.
182
+ rerank: bool = True
183
+ #: Search only the rows the calling account itself owns, by naming the
184
+ #: account in the statement so an index that leads with it can be used.
185
+ #: It can only remove rows: it leaves out what another account shares
186
+ #: with the caller (a room's topics), which the default search returns.
187
+ #: Opt-in. For a caller whose path is one every account has, where the
188
+ #: search would otherwise read every account's rows at that path before
189
+ #: the database's row-level rules discard the others. With
190
+ #: ``include_descendants`` the semantic read is then exact over the
191
+ #: account's rows beneath the path, so its candidates can differ from
192
+ #: those of the same request without this field.
193
+ own_account_only: bool = False
176
194
  #: The calling agent, for the per-agent exploration assignment in the
177
195
  #: recommendation. A fleet whose members pass distinct ids spreads its
178
196
  #: search over the untried actions instead of all trying the same one.
@@ -327,6 +327,40 @@ _model_executor = ThreadPoolExecutor(
327
327
  _db_executor = ThreadPoolExecutor(max_workers=8, thread_name_prefix="amfs-db")
328
328
 
329
329
 
330
+ #: Says whether the cross-encoder ranked a retrieve's results: ``1`` when it
331
+ #: did, ``0`` when it did not (none is installed, it failed, there was nothing
332
+ #: to rank, or the caller declined it). A caller that thresholds on ``_score``
333
+ #: needs to know, since the relevance term is the cross-encoder's standing in
334
+ #: the batch in one case and the embedding similarity in the other.
335
+ RERANKED_HEADER = "X-AMFS-Reranked"
336
+
337
+
338
+ class _Stages:
339
+ """Wall time of a request's stages, for a ``Server-Timing`` header.
340
+
341
+ ``mark(name)`` charges the time since the previous mark to *name*; a name
342
+ marked more than once (a stage inside a loop) accumulates. The header
343
+ carries durations in milliseconds and nothing else: no query text, no
344
+ paths, no counts. It is what lets a slow read be explained from the
345
+ outside, by the caller that waited for it, without a profiler on the
346
+ server.
347
+ """
348
+
349
+ def __init__(self) -> None:
350
+ self._started = self._last = time.perf_counter()
351
+ self._durations: dict[str, float] = {}
352
+
353
+ def mark(self, name: str) -> None:
354
+ now = time.perf_counter()
355
+ self._durations[name] = self._durations.get(name, 0.0) + (now - self._last) * 1000.0
356
+ self._last = now
357
+
358
+ def header(self) -> str:
359
+ parts = [f"{name};dur={ms:.1f}" for name, ms in self._durations.items()]
360
+ parts.append(f"total;dur={(self._last - self._started) * 1000.0:.1f}")
361
+ return ", ".join(parts)
362
+
363
+
330
364
  async def _offload(executor: ThreadPoolExecutor, fn: Any, /, *args: Any, **kwargs: Any) -> Any:
331
365
  """Run ``fn(*args, **kwargs)`` on ``executor`` with the current context."""
332
366
  loop = asyncio.get_running_loop()
@@ -3163,6 +3197,7 @@ async def retrieve_entries(
3163
3197
  from amfs_core.content import ARTIFACT_PENALTY, PROCEDURE_BOOST, classify_artifact
3164
3198
  from amfs_core.query_norm import normalize_temporal
3165
3199
 
3200
+ stages = _Stages()
3166
3201
  branch = _effective_branch(request, req.branch)
3167
3202
  vis = _get_visibility_filter(request)
3168
3203
  embedder = _get_server_embedder()
@@ -3206,6 +3241,7 @@ async def retrieve_entries(
3206
3241
  query_vectors[qtext] = await _offload(_model_executor, embedder.embed, qtext)
3207
3242
  except Exception: # noqa: BLE001
3208
3243
  logger.debug("query embedding failed — adapter will embed", exc_info=True)
3244
+ stages.mark("embed")
3209
3245
  sq = SemanticQuery(
3210
3246
  text=qtext,
3211
3247
  entity_path=req.entity_path,
@@ -3213,6 +3249,7 @@ async def retrieve_entries(
3213
3249
  min_confidence=req.min_confidence,
3214
3250
  limit=pool,
3215
3251
  embedding=query_vectors.get(qtext),
3252
+ own_account_only=req.own_account_only,
3216
3253
  )
3217
3254
  try:
3218
3255
  pairs = await _async_adapter.semantic_search(sq, embedder, branch=branch)
@@ -3225,6 +3262,7 @@ async def retrieve_entries(
3225
3262
  candidates[entry.entry_key] = {"entry": entry, "sim": sim, "keyword": 0.0}
3226
3263
  elif sim > slot["sim"]:
3227
3264
  slot["sim"] = sim
3265
+ stages.mark("semantic")
3228
3266
 
3229
3267
  # 3b. Lexical channel (first-class, always run — OR-tsquery recall).
3230
3268
  sq_lex = SearchQuery(
@@ -3236,6 +3274,7 @@ async def retrieve_entries(
3236
3274
  sort_by="confidence",
3237
3275
  depth=3,
3238
3276
  include_artifacts=req.include_artifacts,
3277
+ own_account_only=req.own_account_only,
3239
3278
  )
3240
3279
  lex_entries: list[MemoryEntry] = []
3241
3280
  if _async_adapter is not None:
@@ -3263,6 +3302,7 @@ async def retrieve_entries(
3263
3302
  candidates.setdefault(
3264
3303
  entry.entry_key, {"entry": entry, "sim": 0.0, "keyword": 1.0}
3265
3304
  )
3305
+ stages.mark("lexical")
3266
3306
 
3267
3307
  # 3d. Below-gate read, scoped to this query. A discredited entry sits under
3268
3308
  # the discredit threshold by definition, so a caller gating at or above
@@ -3288,6 +3328,7 @@ async def retrieve_entries(
3288
3328
  max_confidence=gate_ceiling,
3289
3329
  limit=BELOW_GATE_LIMIT,
3290
3330
  embedding=query_vectors[topical],
3331
+ own_account_only=req.own_account_only,
3291
3332
  ),
3292
3333
  embedder,
3293
3334
  branch=branch,
@@ -3310,6 +3351,7 @@ async def retrieve_entries(
3310
3351
  sort_by="recency",
3311
3352
  depth=3,
3312
3353
  include_artifacts=req.include_artifacts,
3354
+ own_account_only=req.own_account_only,
3313
3355
  )
3314
3356
  lex_below: list[MemoryEntry] = []
3315
3357
  try:
@@ -3330,6 +3372,7 @@ async def retrieve_entries(
3330
3372
  else:
3331
3373
  slot["keyword"] = 1.0
3332
3374
  candidates.update(below_gate)
3375
+ stages.mark("below_gate")
3333
3376
 
3334
3377
  # 4. Drop benchmark/system scratch namespaces from user recall, and the
3335
3378
  # system-written contrast lessons: those are consumed by the briefing
@@ -3612,9 +3655,17 @@ async def retrieve_entries(
3612
3655
  # entries with identical text, one at confidence 0.5 and one at 1.0,
3613
3656
  # ranked with the 0.5 one first. Outcomes were recorded faithfully and
3614
3657
  # then ignored at the only point where they could change behaviour.
3658
+ #
3659
+ # A caller may decline it (``rerank: false``). It is the slowest stage
3660
+ # of a read, and a caller that makes one on every turn of a conversation
3661
+ # can prefer the composite as it stands to waiting for the cross-encoder.
3662
+ # The response says whether it ran, because a score's relevance term
3663
+ # means something different with and without it.
3664
+ stages.mark("score")
3615
3665
  reranker = _retrieval_reranker
3616
3666
  rerank_top_n = 30
3617
- if reranker is not None and getattr(reranker, "available", False) and scored:
3667
+ reranked_by_cross_encoder = False
3668
+ if req.rerank and reranker is not None and getattr(reranker, "available", False) and scored:
3618
3669
  head = scored[:rerank_top_n]
3619
3670
  try:
3620
3671
  # Cross-encoder inference over up to thirty documents: the single
@@ -3657,6 +3708,8 @@ async def retrieve_entries(
3657
3708
  # the two halves back together in order would pin it above anyway.
3658
3709
  scored = reranked + scored[rerank_top_n:]
3659
3710
  scored.sort(key=lambda t: t[1], reverse=True)
3711
+ reranked_by_cross_encoder = True
3712
+ stages.mark("rerank")
3660
3713
 
3661
3714
  # 9. Abstain floor: trim clearly-irrelevant tail (low relevance AND no
3662
3715
  # keyword match), but never drop the single best result.
@@ -4167,6 +4220,11 @@ async def retrieve_entries(
4167
4220
  out.append(data)
4168
4221
  if meta is not None:
4169
4222
  out.append(meta)
4223
+ stages.mark("finish")
4224
+ # A caller invoking the handler in-process has no response to decorate.
4225
+ if response is not None:
4226
+ response.headers[RERANKED_HEADER] = "1" if reranked_by_cross_encoder else "0"
4227
+ response.headers["Server-Timing"] = stages.header()
4170
4228
  return out
4171
4229
 
4172
4230
 
@@ -9834,7 +9892,15 @@ async def ingest_webhook(
9834
9892
  registry = ConnectorRegistry()
9835
9893
  connector = registry.get(connector_name)
9836
9894
  if connector:
9837
- ingester.register_transform("*", connector.transform)
9895
+ # A connector transforms the decoded payload: ConnectorABC.transform
9896
+ # takes the dict, which is what connectors are written and tested
9897
+ # against. The ingester calls its transforms with the WebhookEvent it
9898
+ # built instead, so registering the bound method as-is handed every
9899
+ # connector the event, and PagerDuty's first .get() raised: a 500 on
9900
+ # every delivery.
9901
+ ingester.register_transform(
9902
+ "*", lambda event: connector.transform(event.payload)
9903
+ )
9838
9904
  except Exception:
9839
9905
  pass
9840
9906