amfs-http-server 0.3.62__tar.gz → 0.3.64__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,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: amfs-http-server
3
- Version: 0.3.62
3
+ Version: 0.3.64
4
4
  Summary: AMFS HTTP/REST API server with SSE support
5
5
  License-Expression: Apache-2.0
6
6
  Requires-Python: >=3.11
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "amfs-http-server"
3
- version = "0.3.62"
3
+ version = "0.3.64"
4
4
  description = "AMFS HTTP/REST API server with SSE support"
5
5
  requires-python = ">=3.11"
6
6
  license = "Apache-2.0"
@@ -2088,6 +2088,87 @@ def entry_quality(
2088
2088
  }
2089
2089
 
2090
2090
 
2091
+ class QualityBatchItem(BaseModel):
2092
+ entity_path: str
2093
+ key: str
2094
+
2095
+
2096
+ class QualityBatchRequest(BaseModel):
2097
+ items: list[QualityBatchItem] = Field(..., max_length=2000)
2098
+ branch: str | None = None
2099
+
2100
+
2101
+ @app.post("/api/v1/quality/batch")
2102
+ def entry_quality_batch(
2103
+ request: Request,
2104
+ body: QualityBatchRequest,
2105
+ _auth: str | None = Depends(verify_api_key),
2106
+ ) -> dict[str, Any]:
2107
+ """Quality scores for many entries in one request.
2108
+
2109
+ The topic and agent pages used to ask ``/quality/{path}/{key}`` once per
2110
+ entry, and each of those listed the whole topic again to find the
2111
+ sibling keys — on a 365-entry topic that was 365 round trips of about a
2112
+ second each, serialised three at a time, before the page rendered. Here
2113
+ each topic is listed once and every requested key in it is scored from
2114
+ that one list. An entry that does not exist, or that the caller may not
2115
+ see, comes back with a null score rather than an error, so one bad key
2116
+ does not fail the page.
2117
+ """
2118
+ branch = _effective_branch(request, body.branch)
2119
+ mem = _get_memory()
2120
+ vis = _active_visibility_filter(request)
2121
+ evaluator = HeuristicQualityEvaluator()
2122
+
2123
+ wanted: dict[str, list[str]] = {}
2124
+ for item in body.items:
2125
+ wanted.setdefault(item.entity_path, []).append(item.key)
2126
+
2127
+ scores: dict[tuple[str, str], float | None] = {}
2128
+ for entity_path, keys in wanted.items():
2129
+ # Straight from the adapter, as the single route reads: ``mem.list``
2130
+ # on the server's own handle keeps only shared entries and the
2131
+ # server's, so another agent's private keys — which the topic page
2132
+ # already lists — would come back null. The caller's visibility
2133
+ # rule, applied below, is the only filter that belongs here.
2134
+ try:
2135
+ entries = mem._adapter.list(entity_path, branch=branch)
2136
+ except Exception:
2137
+ logger.debug("quality batch: list failed for %s", entity_path, exc_info=True)
2138
+ entries = []
2139
+ if vis is not None:
2140
+ entries = vis.filter_entries(entries)
2141
+ by_key = {e.key: e for e in entries}
2142
+ all_keys = list(by_key)
2143
+ for key in keys:
2144
+ entry = by_key.get(key)
2145
+ if entry is None:
2146
+ scores[(entity_path, key)] = None
2147
+ continue
2148
+ mt = (
2149
+ entry.memory_type.value
2150
+ if hasattr(entry.memory_type, "value")
2151
+ else str(entry.memory_type)
2152
+ )
2153
+ report = evaluator.evaluate(
2154
+ entry.value,
2155
+ entity_path=entity_path,
2156
+ key=key,
2157
+ confidence=entry.confidence,
2158
+ memory_type=mt,
2159
+ pattern_refs=list(entry.provenance.pattern_refs),
2160
+ existing_keys=[k for k in all_keys if k != key],
2161
+ )
2162
+ scores[(entity_path, key)] = report.score
2163
+
2164
+ return {
2165
+ "results": [
2166
+ {"entity_path": i.entity_path, "key": i.key, "score": scores[(i.entity_path, i.key)]}
2167
+ for i in body.items
2168
+ ]
2169
+ }
2170
+
2171
+
2091
2172
  async def _scope_block(
2092
2173
  entity_path: str,
2093
2174
  key: str,
@@ -8711,29 +8792,132 @@ def graph_backfill(
8711
8792
  # ──────────────────────────────────────────────────────────────────────
8712
8793
 
8713
8794
 
8714
- def _compute_tiers(entries: list) -> tuple[dict[str, int], dict[str, float]]:
8715
- """Score entries and assign HMO tiers (Hot/Warm/Archive)."""
8716
- from amfs_core.tiering import PriorityScorer, TierAssigner
8795
+ def _tier_bands() -> tuple[int, int]:
8796
+ """``(hot_capacity, warm_capacity)``: the tiers are rank bands over the
8797
+ priority order — the top ``hot`` entries are Hot, the next ``warm`` Warm,
8798
+ the rest Archive (``amfs_core.tiering.TierAssigner``)."""
8799
+ from amfs_core.models import TierConfig
8800
+
8801
+ cfg = TierConfig()
8802
+ return int(cfg.hot_capacity), int(cfg.warm_capacity)
8717
8803
 
8718
- scorer = PriorityScorer()
8719
- assigner = TierAssigner()
8720
- return assigner.assign_with_scores(entries, scorer)
8721
8804
 
8805
+ def _tier_split(total: int) -> tuple[int, int, int]:
8806
+ """How many of *total* ranked entries fall in each band."""
8807
+ hot_cap, warm_cap = _tier_bands()
8808
+ hot = min(hot_cap, total)
8809
+ warm = min(warm_cap, max(0, total - hot_cap))
8810
+ return hot, warm, max(0, total - hot_cap - warm_cap)
8722
8811
 
8723
- def _tiered_entries(
8724
- mem: AgentMemory, vis: Any | None, agent_id: str | None
8725
- ) -> tuple[list[MemoryEntry], tuple[dict[str, int], dict[str, float]]]:
8726
- """The entries a tiers page scores, and their tiers and scores.
8727
8812
 
8728
- The tiering is a Python scorer over the whole visible set, so the set has
8729
- to be loaded; this loads only the named agent's rows when there is one
8730
- and runs the load, the visibility pass and the scoring together off the
8731
- event loop. Synchronous: call it via ``_offload``.
8813
+ def _tier_window(tier: int, limit: int) -> tuple[int, int]:
8814
+ """``(offset, limit)`` into the priority ranking for one tier's page."""
8815
+ hot_cap, warm_cap = _tier_bands()
8816
+ if tier == 1:
8817
+ return 0, min(limit, hot_cap)
8818
+ if tier == 2:
8819
+ return hot_cap, min(limit, warm_cap)
8820
+ return hot_cap + warm_cap, limit
8821
+
8822
+
8823
+ #: Entries per round trip when the tiers have to be scored in Python.
8824
+ _TIER_SCAN_PAGE = 2000
8825
+
8826
+
8827
+ def _tier_scan(
8828
+ mem: AgentMemory,
8829
+ agent_id: str | None,
8830
+ *,
8831
+ scope: Any | None,
8832
+ py_filter: Any | None,
8833
+ vis: Any | None,
8834
+ keep: int,
8835
+ ) -> tuple[int, float, list[tuple[float, MemoryEntry]]]:
8836
+ """Score the visible entries a page at a time, keeping only the top *keep*.
8837
+
8838
+ The fallback for a visibility rule that only exists in Python or an
8839
+ adapter that cannot order by the score. Bounded in memory: a page is
8840
+ scored, folded into the count and the running sum, and all but the top
8841
+ *keep* are dropped before the next page is read.
8842
+
8843
+ The caller's visibility is ``(scope, py_filter)`` as ``_visibility_scope``
8844
+ gave it: *scope* narrows each page in SQL, *py_filter* runs over the
8845
+ loaded rows. An adapter that cannot take a scope or page (the in-memory
8846
+ ones) gets one unpaged ``list()``, and then *vis* — the filter object the
8847
+ scope was derived from — runs over it, so a rule that exists only as a
8848
+ predicate is still applied rather than dropped. Returns
8849
+ ``(count, score_sum, top)`` with *top* highest first. Synchronous: call
8850
+ it via ``_offload``.
8732
8851
  """
8733
- entries = _entries_by_agent(mem, agent_id) if agent_id else mem.list()
8734
- if vis is not None:
8735
- entries = vis.filter_entries(entries)
8736
- return entries, _compute_tiers(entries)
8852
+ import heapq
8853
+
8854
+ from amfs_core.tiering import PriorityScorer
8855
+
8856
+ scorer = PriorityScorer()
8857
+ now = datetime.now(UTC)
8858
+ count = 0
8859
+ score_sum = 0.0
8860
+ # A min-heap of (score, tiebreak, entry); the smallest is evicted first.
8861
+ top: list[tuple[float, int, MemoryEntry]] = []
8862
+ seq = 0
8863
+
8864
+ def fold(entries: list[MemoryEntry], rule: Any | None) -> None:
8865
+ nonlocal count, score_sum, seq
8866
+ if rule is not None:
8867
+ entries = rule.filter_entries(entries)
8868
+ for e in entries:
8869
+ if agent_id and e.provenance.agent_id != agent_id:
8870
+ continue
8871
+ s = scorer.score(e, now=now)
8872
+ count += 1
8873
+ score_sum += s
8874
+ seq -= 1 # earlier rows win ties, as the stable sort did
8875
+ item = (s, seq, e)
8876
+ if len(top) < keep:
8877
+ heapq.heappush(top, item)
8878
+ elif item > top[0]:
8879
+ heapq.heapreplace(top, item)
8880
+
8881
+ offset = 0
8882
+ adapter = mem._adapter
8883
+ while True:
8884
+ try:
8885
+ page = adapter.list(
8886
+ agent_id=agent_id, scope=scope, limit=_TIER_SCAN_PAGE, offset=offset
8887
+ )
8888
+ except TypeError:
8889
+ # No scope or paging in this adapter: the whole account, and the
8890
+ # visibility rule — whichever form it took — applied here.
8891
+ rule = py_filter if py_filter is not None else (vis if scope is not None else None)
8892
+ fold(_entries_by_agent(mem, agent_id) if agent_id else mem.list(), rule)
8893
+ break
8894
+ fold(page, py_filter)
8895
+ if len(page) < _TIER_SCAN_PAGE:
8896
+ break
8897
+ offset += _TIER_SCAN_PAGE
8898
+ ranked = sorted(top, reverse=True)
8899
+ return count, score_sum, [(s, e) for s, _, e in ranked]
8900
+
8901
+
8902
+ def _tiers_in_sql(adapter: Any, py_filter: Any | None) -> bool:
8903
+ """Whether the tiers can be read as one ranked page from the database:
8904
+ the adapter orders by the score and no Python-only visibility rule hides
8905
+ an unknown share of the rows."""
8906
+ return py_filter is None and callable(getattr(adapter, "list_by_priority", None))
8907
+
8908
+
8909
+ def _tier_entry_dict(e: MemoryEntry, tier: int, score: float) -> dict[str, Any]:
8910
+ return {
8911
+ "entity_path": e.entity_path,
8912
+ "key": e.key,
8913
+ "confidence": e.confidence,
8914
+ "tier": tier,
8915
+ "priority_score": round(score, 6),
8916
+ "recall_count": getattr(e, "recall_count", 0),
8917
+ "importance_score": getattr(e, "importance_score", None),
8918
+ "written_at": e.provenance.written_at.isoformat(),
8919
+ "agent_id": e.provenance.agent_id,
8920
+ }
8737
8921
 
8738
8922
 
8739
8923
  @app.get("/api/v1/pro/tiers/distribution")
@@ -8742,32 +8926,36 @@ async def tiers_distribution(
8742
8926
  agent_id: str | None = Query(None),
8743
8927
  _auth: str | None = Depends(verify_api_key),
8744
8928
  ) -> dict[str, Any]:
8745
- """Return HMO tier distribution (Hot / Warm / Archive)."""
8746
- entries, (tiers, scores) = await _offload(
8747
- _db_executor, _tiered_entries, _get_memory(), _active_visibility_filter(request), agent_id
8748
- )
8749
-
8750
- hot = warm = archive = scored_count = 0
8751
- score_sum = 0.0
8752
- for key, tier in tiers.items():
8753
- if tier == 1:
8754
- hot += 1
8755
- elif tier == 2:
8756
- warm += 1
8757
- else:
8758
- archive += 1
8759
- s = scores.get(key)
8760
- if s is not None:
8761
- scored_count += 1
8762
- score_sum += s
8929
+ """Return HMO tier distribution (Hot / Warm / Archive).
8930
+
8931
+ The tiers are rank bands over the priority score, so the distribution is
8932
+ a count and a mean: the database computes both (``priority_stats``) and
8933
+ no entry is loaded. The previous version listed the whole account and
8934
+ scored it in Python; on a 420K-entry account the two requests the tiers
8935
+ page makes together exhausted an 8 GiB instance and took every other
8936
+ request on it down with them.
8937
+ """
8938
+ mem = _get_memory()
8939
+ scope, py_filter = _visibility_scope(request)
8940
+ if _tiers_in_sql(mem._adapter, py_filter):
8941
+ total, mean = await _offload(
8942
+ _db_executor, mem._adapter.priority_stats, scope=scope, agent_id=agent_id
8943
+ )
8944
+ else:
8945
+ total, score_sum, _top = await _offload(
8946
+ _db_executor, _tier_scan, mem, agent_id,
8947
+ scope=scope, py_filter=py_filter, vis=_active_visibility_filter(request), keep=1,
8948
+ )
8949
+ mean = score_sum / total if total else None
8763
8950
 
8951
+ hot, warm, archive = _tier_split(total)
8764
8952
  return {
8765
- "total": len(entries),
8953
+ "total": total,
8766
8954
  "hot": hot,
8767
8955
  "warm": warm,
8768
8956
  "archive": archive,
8769
- "scored": scored_count,
8770
- "avg_priority_score": round(score_sum / scored_count, 6) if scored_count else None,
8957
+ "scored": total,
8958
+ "avg_priority_score": round(mean, 6) if mean is not None else None,
8771
8959
  }
8772
8960
 
8773
8961
 
@@ -8779,28 +8967,28 @@ async def tiers_entries(
8779
8967
  agent_id: str | None = Query(None),
8780
8968
  _auth: str | None = Depends(verify_api_key),
8781
8969
  ) -> list[dict[str, Any]]:
8782
- """Return entries for a given HMO tier as a flat array."""
8783
- entries, (tier_map, score_map) = await _offload(
8784
- _db_executor, _tiered_entries, _get_memory(), _active_visibility_filter(request), agent_id
8785
- )
8786
-
8787
- filtered = [e for e in entries if tier_map.get(e.entry_key) == tier]
8788
- filtered.sort(key=lambda e: score_map.get(e.entry_key, 0.0), reverse=True)
8970
+ """Return entries for a given HMO tier as a flat array, highest priority
8971
+ first. One page of the ranking, read at the tier's offset."""
8972
+ mem = _get_memory()
8973
+ scope, py_filter = _visibility_scope(request)
8974
+ offset, page = _tier_window(tier, limit)
8975
+ if _tiers_in_sql(mem._adapter, py_filter):
8976
+ from amfs_core.tiering import PriorityScorer
8977
+
8978
+ now = datetime.now(UTC)
8979
+ entries = await _offload(
8980
+ _db_executor, mem._adapter.list_by_priority,
8981
+ scope=scope, agent_id=agent_id, limit=page, offset=offset, now=now,
8982
+ )
8983
+ scorer = PriorityScorer()
8984
+ return [_tier_entry_dict(e, tier, scorer.score(e, now=now)) for e in entries]
8789
8985
 
8790
- return [
8791
- {
8792
- "entity_path": e.entity_path,
8793
- "key": e.key,
8794
- "confidence": e.confidence,
8795
- "tier": tier,
8796
- "priority_score": round(score_map.get(e.entry_key, 0.0), 6),
8797
- "recall_count": getattr(e, "recall_count", 0),
8798
- "importance_score": getattr(e, "importance_score", None),
8799
- "written_at": e.provenance.written_at.isoformat(),
8800
- "agent_id": e.provenance.agent_id,
8801
- }
8802
- for e in filtered[:limit]
8803
- ]
8986
+ _count, _sum, top = await _offload(
8987
+ _db_executor, _tier_scan, mem, agent_id,
8988
+ scope=scope, py_filter=py_filter, vis=_active_visibility_filter(request),
8989
+ keep=offset + page,
8990
+ )
8991
+ return [_tier_entry_dict(e, tier, s) for s, e in top[offset:offset + page]]
8804
8992
 
8805
8993
 
8806
8994
  # ──────────────────────────────────────────────────────────────────────