amfs-http-server 0.3.69__tar.gz → 0.3.71__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.69
3
+ Version: 0.3.71
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.58
8
- Requires-Dist: amfs>=0.5.43
7
+ Requires-Dist: amfs-core>=0.3.59
8
+ Requires-Dist: amfs>=0.5.45
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.69"
3
+ version = "0.3.71"
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.43",
16
+ "amfs>=0.5.45",
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.58",
30
+ "amfs-core>=0.3.59",
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
@@ -50,6 +50,7 @@ from amfs_core.aggregates import (
50
50
  )
51
51
  from amfs_core.ranking import composite_score
52
52
  from amfs_core.ranking import entry_text as _entry_text
53
+ from amfs_core.models import readable_by as _readable_by
53
54
  from amfs_core.scope import SqlScope, covers
54
55
  from amfs_core.ranking import keyword_coverage as _keyword_coverage
55
56
  from amfs_core.reuse_value import REUSE_VALUE_HEADER, reuse_value_block
@@ -611,6 +612,63 @@ def _rerank_is_calibrated(scores: list[float]) -> bool:
611
612
  RERANK_ENDORSED = 0.5
612
613
 
613
614
 
615
+ def _reuse_credit_gated() -> bool:
616
+ """Whether a retrieve hit must be endorsed to count as a reuse (default).
617
+
618
+ ``AMFS_REUSE_CREDIT_GATE=off`` restores crediting the top hit of every
619
+ retrieve without a code deploy. See :func:`_reuse_creditable` for what
620
+ the default costs and why it is the default all the same.
621
+ """
622
+ return os.environ.get("AMFS_REUSE_CREDIT_GATE", "").strip().lower() not in (
623
+ "0", "off", "false", "no",
624
+ )
625
+
626
+
627
+ def _reuse_creditable(breakdown: dict[str, Any]) -> bool:
628
+ """Whether a retrieve hit may be counted as a memory that was reused.
629
+
630
+ Counting it bumps the entry's ``recall_count``, writes a reuse event and
631
+ returns the block a client relays to its user as what memory just did for
632
+ them. All three say the hit was about the query, so the test is whether
633
+ anything here can vouch for that:
634
+
635
+ * The composite score cannot. It blends confidence, recency and evidence
636
+ with relevance, and it ranks: the best of a bad batch is still first.
637
+ * The bi-encoder's similarity cannot. Measured with the default embedder
638
+ on real queries, the top hits that had nothing to do with the query sat
639
+ at 0.64-0.66 cosine and the ones that answered it at 0.60-0.80.
640
+ * The lexical term cannot. It is coverage within the candidate pool, so
641
+ the one candidate holding the query's only matched word scores 1.0.
642
+ * The cross-encoder's absolute score (``rerank_absolute``) can, in one
643
+ direction. On the same queries every unrelated top hit scored under
644
+ 0.01, and the specific questions' hits over 0.9.
645
+
646
+ So a hit is credited when the cross-encoder puts it at better-than-even
647
+ odds (``RERANK_ENDORSED``, the bar step 9 already uses to overrule the
648
+ abstain floor). The cost is on the other side and is real: a relevant hit
649
+ to an open-ended question ("anything I should know before touching X")
650
+ scored under 0.01 too, in two of seven relevant cases. Those reuses go
651
+ uncounted. That is the error this number can afford: it is an estimate
652
+ shown to a person as a saving, and one unrelated row counted as a saving
653
+ costs it more belief than a real one left out.
654
+
655
+ Where no cross-encoder judged the hit there is nothing to gate on and it
656
+ is credited as before: a deployment without a reranker, a request that
657
+ declined it (``rerank: false``), a hit past the reranked head, and a
658
+ branch's pinned entry, which is at the head because the branch put it
659
+ there.
660
+ """
661
+ if not _reuse_credit_gated():
662
+ return True
663
+ absolute = breakdown.get("rerank_absolute")
664
+ if absolute is None:
665
+ return True
666
+ try:
667
+ return float(absolute) >= RERANK_ENDORSED
668
+ except (TypeError, ValueError):
669
+ return True
670
+
671
+
614
672
  def _rerank_absolute(scores: list[float]) -> list[float]:
615
673
  """The cross-encoder's opinion of each candidate on its own, 0..1.
616
674
 
@@ -1008,6 +1066,7 @@ async def _branch_treatment(
1008
1066
  vis: Any,
1009
1067
  include_artifacts: bool,
1010
1068
  is_artifact: Callable[[MemoryEntry], bool],
1069
+ reader: str | None = None,
1011
1070
  ) -> list[tuple[MemoryEntry, float, float]]:
1012
1071
  """The entries *branch* changed under *entity_path* that are about *topical*.
1013
1072
 
@@ -1051,7 +1110,7 @@ async def _branch_treatment(
1051
1110
  pairs = await _async_adapter.semantic_search(
1052
1111
  SemanticQuery(
1053
1112
  text=topical, entity_path=entity_path, min_confidence=0.0,
1054
- limit=pool, embedding=query_vector,
1113
+ limit=pool, embedding=query_vector, visible_to_agent=reader,
1055
1114
  ),
1056
1115
  embedder,
1057
1116
  branch=branch,
@@ -1067,6 +1126,7 @@ async def _branch_treatment(
1067
1126
  lex = SearchQuery(
1068
1127
  query=topical, entity_path=entity_path, min_confidence=0.0, limit=pool,
1069
1128
  sort_by="confidence", depth=3, include_artifacts=include_artifacts,
1129
+ visible_to_agent=reader,
1070
1130
  )
1071
1131
  try:
1072
1132
  if _async_adapter is not None:
@@ -1095,7 +1155,7 @@ async def _branch_treatment(
1095
1155
  # sees the record; it is not hidden from the arm on the record's account.
1096
1156
  out = [
1097
1157
  t for t in found.values()
1098
- if include_artifacts or not is_artifact(t[0])
1158
+ if (include_artifacts or not is_artifact(t[0])) and _readable_by(t[0], reader)
1099
1159
  ]
1100
1160
  if out and vis is not None and vis.should_filter():
1101
1161
  allowed = {e.entry_key for e in vis.filter_entries([t[0] for t in out])}
@@ -1111,6 +1171,7 @@ async def _discredited_below_gate(
1111
1171
  vis: Any,
1112
1172
  include_artifacts: bool,
1113
1173
  limit: int,
1174
+ reader: str | None = None,
1114
1175
  ) -> list[MemoryEntry]:
1115
1176
  """The entity's discredited entries the ranked list did not hold.
1116
1177
 
@@ -1130,9 +1191,12 @@ async def _discredited_below_gate(
1130
1191
  confidence at or under the discredit threshold — a small set, since that is
1131
1192
  what discrediting means — then the discredited ones among them.
1132
1193
 
1133
- Filtered by the same visibility rules as the ranked list. The rows are not
1134
- returned, but the recommendation they steer is, and a policy decision
1135
- driven by memory the caller cannot see is a leak by another name.
1194
+ Filtered by the same visibility rules as the ranked list, *reader*'s
1195
+ included: another agent's private entry is left out in the query, so it
1196
+ takes none of *limit*, and again on what comes back, for a store that
1197
+ does not apply it. The rows are not returned, but the recommendation they
1198
+ steer is, and a policy decision driven by memory the caller cannot see is
1199
+ a leak by another name.
1136
1200
  Best-effort; a store that cannot answer contributes nothing rather than
1137
1201
  failing the retrieve.
1138
1202
  """
@@ -1144,6 +1208,7 @@ async def _discredited_below_gate(
1144
1208
  sort_by="recency",
1145
1209
  depth=3,
1146
1210
  include_artifacts=include_artifacts,
1211
+ visible_to_agent=reader,
1147
1212
  )
1148
1213
  rows: list[MemoryEntry] = []
1149
1214
  try:
@@ -1163,6 +1228,7 @@ async def _discredited_below_gate(
1163
1228
  return [
1164
1229
  e for e in rows
1165
1230
  if getattr(e, "discredited_at", None) is not None
1231
+ and _readable_by(e, reader)
1166
1232
  and e.entry_key not in seen
1167
1233
  and not _is_excluded_entity(getattr(e, "entity_path", ""))
1168
1234
  and not _is_synthetic_key(getattr(e, "key", ""))
@@ -3030,6 +3096,23 @@ def _known_agent_id(value: str | None) -> str | None:
3030
3096
  return cleaned or None
3031
3097
 
3032
3098
 
3099
+ def _reading_agent(request: Request) -> str | None:
3100
+ """The agent a read is made for, or ``None`` when the request names none.
3101
+
3102
+ The ``X-AMFS-Agent-Id`` header and nothing else. It is the identity of the
3103
+ session, sent on every request by the HTTP adapter and the MCP gateway,
3104
+ which are the clients whose ``read``, ``list`` and ``search`` already keep
3105
+ another agent's private entries from it. A retrieve's body can carry an
3106
+ ``agent_id`` too, but that one is there to spread a fleet over untried
3107
+ actions and is sent by services that read on an account's behalf; taking
3108
+ it for the reader would hide rows from callers that never asked to be
3109
+ treated as an agent. Read defensively because this route is also called
3110
+ in-process, with a request built by the caller.
3111
+ """
3112
+ headers = getattr(request, "headers", None)
3113
+ return _known_agent_id(headers.get("x-amfs-agent-id") if headers is not None else None)
3114
+
3115
+
3033
3116
  def _persist_reuse_event(
3034
3117
  credited: MemoryEntry,
3035
3118
  *,
@@ -3201,6 +3284,16 @@ async def retrieve_entries(
3201
3284
  branch = _effective_branch(request, req.branch)
3202
3285
  vis = _get_visibility_filter(request)
3203
3286
  embedder = _get_server_embedder()
3287
+ # The agent this is read for, when the request names one. An entry written
3288
+ # with ``shared=False`` is its author's alone: ``read``, ``list`` and
3289
+ # ``search`` have always kept it from other agents, and this route handed
3290
+ # it back in full, so the one way to find a memory by meaning was also the
3291
+ # one way to read what an agent had marked private. The rule goes into the
3292
+ # statements below (before the limit, so private rows do not use up the
3293
+ # pool) and is applied once more over the merged set in step 5. A request
3294
+ # that names no agent is not an agent's read (an admin page, a service
3295
+ # calling with the account's key) and is answered as before.
3296
+ reader = _reading_agent(request)
3204
3297
 
3205
3298
  # 1. Split temporal intent out of the query so it becomes a recency signal
3206
3299
  # rather than embedded/lexical noise.
@@ -3250,6 +3343,7 @@ async def retrieve_entries(
3250
3343
  limit=pool,
3251
3344
  embedding=query_vectors.get(qtext),
3252
3345
  own_account_only=req.own_account_only,
3346
+ visible_to_agent=reader,
3253
3347
  )
3254
3348
  try:
3255
3349
  pairs = await _async_adapter.semantic_search(sq, embedder, branch=branch)
@@ -3275,6 +3369,7 @@ async def retrieve_entries(
3275
3369
  depth=3,
3276
3370
  include_artifacts=req.include_artifacts,
3277
3371
  own_account_only=req.own_account_only,
3372
+ visible_to_agent=reader,
3278
3373
  )
3279
3374
  lex_entries: list[MemoryEntry] = []
3280
3375
  if _async_adapter is not None:
@@ -3329,6 +3424,7 @@ async def retrieve_entries(
3329
3424
  limit=BELOW_GATE_LIMIT,
3330
3425
  embedding=query_vectors[topical],
3331
3426
  own_account_only=req.own_account_only,
3427
+ visible_to_agent=reader,
3332
3428
  ),
3333
3429
  embedder,
3334
3430
  branch=branch,
@@ -3352,6 +3448,7 @@ async def retrieve_entries(
3352
3448
  depth=3,
3353
3449
  include_artifacts=req.include_artifacts,
3354
3450
  own_account_only=req.own_account_only,
3451
+ visible_to_agent=reader,
3355
3452
  )
3356
3453
  lex_below: list[MemoryEntry] = []
3357
3454
  try:
@@ -3402,6 +3499,13 @@ async def retrieve_entries(
3402
3499
  candidates = {k: v for k, v in candidates.items() if k in allowed}
3403
3500
  lessons = vis.filter_entries(lessons) if lessons else lessons
3404
3501
 
3502
+ # 5b. Another agent's private entries, for the reads that did not state the
3503
+ # rule themselves: the sync fallback on an adapter with no SQL to put
3504
+ # it in. A no-op after the Postgres reads above, which already did.
3505
+ if reader:
3506
+ candidates = {k: v for k, v in candidates.items() if _readable_by(v["entry"], reader)}
3507
+ lessons = [e for e in lessons if _readable_by(e, reader)]
3508
+
3405
3509
  # 6. Artifact awareness (column authoritative once backfilled; classify on
3406
3510
  # the fly otherwise so demotion works immediately).
3407
3511
  col_ready = getattr(_async_adapter, "_has_is_artifact_col", False)
@@ -3787,6 +3891,7 @@ async def retrieve_entries(
3787
3891
  vis=vis,
3788
3892
  include_artifacts=req.include_artifacts,
3789
3893
  is_artifact=_is_artifact,
3894
+ reader=reader,
3790
3895
  )
3791
3896
  if pinned:
3792
3897
  if environment:
@@ -3853,9 +3958,19 @@ async def retrieve_entries(
3853
3958
  # happened (a real session: 4 lookups, 16 credited reuses, 1 that
3854
3959
  # changed the agent's behavior). Best-effort: never let accounting
3855
3960
  # failure affect the response.
3961
+ #
3962
+ # And only a hit the query was about. The top of a ranked list is
3963
+ # there whatever the query: step 9 never drops the single best result,
3964
+ # so a question the store has nothing on still has a first row, and
3965
+ # that row was counted as a memory reused, with its tokens saved and a
3966
+ # line telling the user so. ``_reuse_creditable`` is the test, and it
3967
+ # says why the cross-encoder's own opinion is the only signal here
3968
+ # that can make it.
3856
3969
  credited_entry = None
3857
3970
  credited_hits = 0
3858
3971
  for entry, _score, _bd in scored[:REUSE_CREDIT_K]:
3972
+ if not _reuse_creditable(_bd):
3973
+ continue
3859
3974
  credited_hits += 1
3860
3975
  if credited_entry is None:
3861
3976
  credited_entry = entry
@@ -3995,6 +4110,7 @@ async def retrieve_entries(
3995
4110
  vis=vis,
3996
4111
  include_artifacts=req.include_artifacts,
3997
4112
  limit=pool,
4113
+ reader=reader,
3998
4114
  )
3999
4115
  )
4000
4116
  shifted_entries = [e for e in shift_pool if _regime_shifted(e, now=now)]
@@ -5231,13 +5347,18 @@ async def _memories_matching_task(
5231
5347
  query = normalize_temporal(text).topical
5232
5348
 
5233
5349
  embedder = _get_server_embedder()
5350
+ # Retrieve hides another agent's private entries from the agent asking, so
5351
+ # this does too: the count is of what that agent would have been shown.
5352
+ reader = _reading_agent(request)
5234
5353
  # entry_key -> {"entry", "sim", "keyword"}, the same slot shape retrieve uses.
5235
5354
  candidates: dict[str, dict[str, Any]] = {}
5236
5355
 
5237
5356
  if embedder is not None:
5238
5357
  try:
5239
5358
  pairs = await _async_adapter.semantic_search(
5240
- SemanticQuery(text=query, limit=150), embedder, branch=branch
5359
+ SemanticQuery(text=query, limit=150, visible_to_agent=reader),
5360
+ embedder,
5361
+ branch=branch,
5241
5362
  )
5242
5363
  except Exception: # noqa: BLE001 - a gap report never costs a commit
5243
5364
  logger.debug("gap semantic_search failed", exc_info=True)
@@ -5256,7 +5377,9 @@ async def _memories_matching_task(
5256
5377
  # blindest about the memories that earned their confidence.
5257
5378
  try:
5258
5379
  lex = await _async_adapter.search(
5259
- SearchQuery(query=query, limit=150, sort_by="confidence", depth=3),
5380
+ SearchQuery(
5381
+ query=query, limit=150, sort_by="confidence", depth=3, visible_to_agent=reader,
5382
+ ),
5260
5383
  branch=branch,
5261
5384
  )
5262
5385
  except Exception: # noqa: BLE001