amfs-http-server 0.3.67__tar.gz → 0.3.69__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,11 +1,11 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: amfs-http-server
3
- Version: 0.3.67
3
+ Version: 0.3.69
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
8
- Requires-Dist: amfs>=0.5.42
7
+ Requires-Dist: amfs-core>=0.3.58
8
+ Requires-Dist: amfs>=0.5.43
9
9
  Requires-Dist: fastapi>=0.115
10
10
  Requires-Dist: httpx>=0.27
11
11
  Requires-Dist: sse-starlette>=2.0
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "amfs-http-server"
3
- version = "0.3.67"
3
+ version = "0.3.69"
4
4
  description = "AMFS HTTP/REST API server with SSE support"
5
5
  requires-python = ">=3.11"
6
6
  license = "Apache-2.0"
@@ -13,7 +13,7 @@ dependencies = [
13
13
  # this tree is what test_dependency_floors forbids.
14
14
  # 0.5.18 for AgentMemory.as_agent, which the agent detail page calls to list
15
15
  # an agent's entries as that agent rather than as the server.
16
- "amfs>=0.5.42",
16
+ "amfs>=0.5.43",
17
17
  # 0.3.23 is real in the silent way: the write path calls
18
18
  # adapter.scope_counts(), which is a default on AdapterABC from 0.3.23. On an
19
19
  # older core the adapters that do not override it — filesystem, S3 — have no
@@ -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.58",
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
@@ -59,8 +59,19 @@ class OutcomeRequest(BaseModel):
59
59
  #: trace for one outcome. Only the SDK sets this, and only because its
60
60
  #: ``commit_outcome`` posts the trace on every path out of itself.
61
61
  trace_follows: bool = False
62
+ #: The subset of ``causal_entry_keys`` the session only had in view: read,
63
+ #: and not named by the agent as what it acted on. A failure lowers an
64
+ #: in-view entry without discrediting one that has never failed before.
65
+ #: Absent (an older client, a direct REST caller) means every key is
66
+ #: charged in full, as it always was.
67
+ in_view_entry_keys: list[str] | None = None
68
+ #: For a failed outcome: the entries the agent did not follow, when that
69
+ #: is why it failed. Credited instead of charged; never also charged.
70
+ not_followed_entry_keys: list[str] | None = None
62
71
  #: Failed attempts that preceded the terminal outcome, oldest first:
63
- #: ``{attempt, outcome_type, causal_entry_keys, action_indices, summary}``.
72
+ #: ``{attempt, outcome_type, causal_entry_keys, action_indices, summary}``,
73
+ #: and optionally each attempt's own ``in_view_entry_keys`` and
74
+ #: ``not_followed_entry_keys``.
64
75
  #: Each is applied to its own causal entries before ``outcome_type`` is
65
76
  #: applied to ``causal_entry_keys`` — inside this one outcome and trace.
66
77
  attempts: list[dict[str, Any]] = Field(default_factory=list)
@@ -173,6 +184,24 @@ class RetrieveRequest(BaseModel):
173
184
  #: a memory the record has confirmed does not need nine alternatives beside
174
185
  #: it in the prompt. Opt-in.
175
186
  adaptive_k: bool = False
187
+ #: Rank the head of the results with the cross-encoder where one is
188
+ #: installed (the default, and what every caller got before this field
189
+ #: existed). Set to False to skip it: the cross-encoder is the slowest
190
+ #: stage of a read, and a caller that reads on every turn of a
191
+ #: conversation can prefer the blended score as it stands. The
192
+ #: ``X-AMFS-Reranked`` response header says whether it ran.
193
+ rerank: bool = True
194
+ #: Search only the rows the calling account itself owns, by naming the
195
+ #: account in the statement so an index that leads with it can be used.
196
+ #: It can only remove rows: it leaves out what another account shares
197
+ #: with the caller (a room's topics), which the default search returns.
198
+ #: Opt-in. For a caller whose path is one every account has, where the
199
+ #: search would otherwise read every account's rows at that path before
200
+ #: the database's row-level rules discard the others. With
201
+ #: ``include_descendants`` the semantic read is then exact over the
202
+ #: account's rows beneath the path, so its candidates can differ from
203
+ #: those of the same request without this field.
204
+ own_account_only: bool = False
176
205
  #: The calling agent, for the per-agent exploration assignment in the
177
206
  #: recommendation. A fleet whose members pass distinct ids spreads its
178
207
  #: 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
 
@@ -5367,6 +5425,16 @@ async def commit_outcome(
5367
5425
  final_action_index=final_action_index,
5368
5426
  # The client's read versions, never the server's shared tracker.
5369
5427
  causal_entry_versions=req.causal_entry_versions or {},
5428
+ # The client's statement of each key's role. With explicit keys and
5429
+ # no ``in_view_entry_keys`` (an older client) nothing is in view and
5430
+ # every key is charged in full, as before; with no keys at all the
5431
+ # handle falls back to its read log, and those are in view.
5432
+ in_view_entry_keys=(
5433
+ req.in_view_entry_keys
5434
+ if req.in_view_entry_keys is not None or req.causal_entry_keys is None
5435
+ else []
5436
+ ),
5437
+ not_followed_entry_keys=req.not_followed_entry_keys or [],
5370
5438
  # Action-level learning. Derived from the request's own tool calls
5371
5439
  # and attempts when the client did not send them, never from the
5372
5440
  # shared tracker; the keys are scanned inside commit_outcome.