amfs-http-server 0.3.64__tar.gz → 0.3.66__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.64
3
+ Version: 0.3.66
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.53
8
- Requires-Dist: amfs>=0.5.40
7
+ Requires-Dist: amfs-core>=0.3.55
8
+ Requires-Dist: amfs>=0.5.42
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.64"
3
+ version = "0.3.66"
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.40",
16
+ "amfs>=0.5.42",
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.53",
30
+ "amfs-core>=0.3.55",
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
@@ -81,6 +81,11 @@ class OutcomeRequest(BaseModel):
81
81
  entity_path: str | None = None
82
82
  #: Optional label for the kind of task ("card-declined ticket").
83
83
  situation: str | None = None
84
+ #: What this task was like, as the run declared it (``{"plan": "pro"}``):
85
+ #: scalars keyed by name. Stored on the outcome row as its own block;
86
+ #: a contested situation is split on these, never on the attribute bag's
87
+ #: bookkeeping.
88
+ covariates: dict[str, Any] | None = None
84
89
 
85
90
 
86
91
  class SearchRequest(BaseModel):
@@ -185,6 +190,11 @@ class RetrieveRequest(BaseModel):
185
190
  #: What kind of task this is, embedded for the priors' nearest-neighbour
186
191
  #: lookup in place of the query when given.
187
192
  situation: str | None = None
193
+ #: What this task is like, as scalars (``{"plan": "pro"}``). When the
194
+ #: situation's record has split on one of them — the old action still
195
+ #: wins on one side and lost on the other — the recommendation is read
196
+ #: for this task's side instead of served as contested.
197
+ covariates: dict[str, Any] | None = None
188
198
  #: Return the fields an agent acts on and drop the bookkeeping (score
189
199
  #: breakdown, importance dimensions, integrity fields, long values trimmed).
190
200
  #: Roughly a third of the tokens of the full payload.
@@ -56,6 +56,7 @@ from amfs_core.reuse_value import REUSE_VALUE_HEADER, reuse_value_block
56
56
  from amfs_core.capture import scan_captured_arguments, scan_captured_text
57
57
  from amfs_core.actions import CONTRAST_MIN_W as _CONTRAST_MIN_W
58
58
  from amfs_core.actions import actions_taken as derive_actions_taken
59
+ from amfs_core.actions import normalize_covariates
59
60
  from amfs_core.engine import read_tracker_scope
60
61
  from amfs_core.evidence import evidence_signal as _evidence_signal
61
62
  from amfs_core.evidence import is_success as _evidence_is_success
@@ -1193,6 +1194,7 @@ def _priors_for_retrieve(
1193
1194
  environment: Mapping[str, Any] | None = None,
1194
1195
  query_vector: list[float] | None = None,
1195
1196
  situation: str | None = None,
1197
+ covariates: Mapping[str, Any] | None = None,
1196
1198
  ) -> dict[str, Any] | None:
1197
1199
  """Action priors for ``entity_path`` on tasks like ``text``.
1198
1200
 
@@ -1261,33 +1263,53 @@ def _priors_for_retrieve(
1261
1263
  mine: list[dict[str, Any]] | None = None
1262
1264
  others: list[dict[str, Any]] = []
1263
1265
  elsewhere_rows: list[dict[str, Any]] = []
1264
- declared = _fold_situation(situation)
1266
+ declared = _fold_situation(situation, covariates)
1267
+ identity: dict[str, str] = {}
1268
+ canonical = declared
1265
1269
  if declared and callable(stats):
1266
- # The situation's own record is an equality, not a neighbourhood.
1267
- # The embedding neighbourhood may hold none of it — a queue whose
1268
- # classes embed far apart returns no neighbour above the floor for a
1269
- # class seen once — and the fallback to the entity's whole record
1270
- # would then serve another class's winner as ``act``. Measured on
1271
- # the ops-queue support demo (2026-09-22): the first Android ticket
1272
- # was told ``act: explain_and_close`` from the webhook class's record
1273
- # and spent its three attempts on the entity's winners. So the exact
1274
- # rows come from the entity's record by situation, whatever the
1275
- # neighbourhood found; the neighbourhood supplies ``nearby``.
1276
- exact_rows = [r for r in rows if _fold_situation(r.get("situation")) == declared]
1277
- # The same scan gives the record *elsewhere* — the entity's other
1278
- # situations — which is what orders a sweep over the untried
1279
- # (``amfs_core.actions.sweep_order``).
1270
+ # The situation's own record is read by *identity*, not from the
1271
+ # neighbourhood. The embedding neighbourhood may hold none of it — a
1272
+ # queue whose classes embed far apart returns no neighbour above the
1273
+ # floor for a class seen once — and the fallback to the entity's
1274
+ # whole record would then serve another class's winner as ``act``.
1275
+ # Measured on the ops-queue support demo (2026-09-22): the first
1276
+ # Android ticket was told ``act: explain_and_close`` from the webhook
1277
+ # class's record and spent its three attempts on the entity's
1278
+ # winners. So the situation's rows come from the entity's record by
1279
+ # label, whatever the neighbourhood found; the neighbourhood supplies
1280
+ # ``nearby``.
1281
+ #
1282
+ # Identity, not equality: an agent spells one situation many ways
1283
+ # (``csv export timeout`` / ``csv export timeout web`` / ``web data
1284
+ # export timeout large date range`` — 14 spellings per class per
1285
+ # cell on the 2026-10-21 regime study), and compared as folded
1286
+ # strings the record was non-empty on 37 % of first searches after a
1287
+ # change and the recommendation abstained on 70 %. The record's
1288
+ # labels are joined under ``amfs_core.situations`` (token rule, first
1289
+ # spelling canonical, a hosted resolver for synonyms) and the declared
1290
+ # label is read against those canonicals: 93 % non-empty on the same
1291
+ # searches.
1292
+ scanned: list[dict[str, Any]] = []
1280
1293
  try:
1281
- seen = {r.get("outcome_ref") for r in exact_rows}
1282
- for r in stats(entity_path, limit=SITUATION_RECORD_SCAN):
1283
- if _fold_situation(r.get("situation")) == declared:
1284
- if r.get("outcome_ref") not in seen:
1285
- exact_rows.append(r)
1286
- seen.add(r.get("outcome_ref"))
1287
- else:
1288
- elsewhere_rows.append(r)
1294
+ scanned = list(stats(entity_path, limit=SITUATION_RECORD_SCAN))
1289
1295
  except Exception: # noqa: BLE001
1290
1296
  logger.debug("action_stats by situation failed", exc_info=True)
1297
+ identity = _situation_identity(scanned, rows)
1298
+ canonical = _resolve_situation(declared, identity)
1299
+ exact_rows = [
1300
+ r for r in rows if _canonical_situation(r, identity) == canonical
1301
+ ]
1302
+ # The same scan gives the record *elsewhere* — the entity's other
1303
+ # situations — which is what orders a sweep over the untried
1304
+ # (``amfs_core.actions.sweep_order``).
1305
+ seen = {r.get("outcome_ref") for r in exact_rows}
1306
+ for r in scanned:
1307
+ if _canonical_situation(r, identity) == canonical:
1308
+ if r.get("outcome_ref") not in seen:
1309
+ exact_rows.append(r)
1310
+ seen.add(r.get("outcome_ref"))
1311
+ else:
1312
+ elsewhere_rows.append(r)
1291
1313
  # Partitioned when the situation has a record, or the neighbourhood
1292
1314
  # itself carries labels (so an empty record means "not seen yet",
1293
1315
  # not "older clients"). Labels found only elsewhere on the entity do
@@ -1301,12 +1323,12 @@ def _priors_for_retrieve(
1301
1323
  # pooled as for an undeclared situation. Only ever a question for a
1302
1324
  # situation with no match: a label that has matched is a class for
1303
1325
  # this caller, whatever other clients put in theirs.
1304
- if labelled and not exact_rows and not _labels_are_classes(elsewhere_rows):
1326
+ if labelled and not exact_rows and not _labels_are_classes(elsewhere_rows, identity):
1305
1327
  labelled = False
1306
1328
  if labelled:
1307
1329
  mine = exact_rows
1308
1330
  others = (
1309
- [r for r in rows if _fold_situation(r.get("situation")) != declared]
1331
+ [r for r in rows if _canonical_situation(r, identity) != canonical]
1310
1332
  if source == "similar_outcomes" else []
1311
1333
  )
1312
1334
  if not rows and mine is None:
@@ -1316,8 +1338,16 @@ def _priors_for_retrieve(
1316
1338
  mine, candidate_actions=candidate_actions, environment=environment or None,
1317
1339
  situation_exact=True,
1318
1340
  )
1319
- block["situation_record"] = {"situation": str(situation)[:200], "outcomes": len(mine)}
1320
- block["nearby"] = _nearby_record(others, environment=environment or None)
1341
+ record: dict[str, Any] = {"situation": str(situation)[:200], "outcomes": len(mine)}
1342
+ spellings = sorted({_row_fold(r) for r in mine if r.get("situation")})
1343
+ if len(spellings) > 1 or (spellings and spellings[0] != declared):
1344
+ # What the record was read as: the spellings this label was
1345
+ # joined with, so a reader can see the identity and a benchmark
1346
+ # can measure its purity.
1347
+ record["canonical"] = canonical[:200]
1348
+ record["spellings"] = len(spellings)
1349
+ block["situation_record"] = record
1350
+ block["nearby"] = _nearby_record(others, environment=environment or None, identity=identity)
1321
1351
  if elsewhere_rows:
1322
1352
  elsewhere = aggregate_priors(elsewhere_rows, environment=environment or None)
1323
1353
  block["elsewhere"] = {
@@ -1357,51 +1387,91 @@ LABELS_MIN_ROWS = 20
1357
1387
  LABELS_MAX_DISTINCT_RATIO = 0.9
1358
1388
 
1359
1389
 
1360
- def _labels_are_classes(rows: Sequence[Mapping[str, Any]]) -> bool:
1390
+ def _labels_are_classes(
1391
+ rows: Sequence[Mapping[str, Any]], identity: Mapping[str, str] | None = None,
1392
+ ) -> bool:
1361
1393
  """Whether the situations on *rows* recur — a class label — rather than
1362
1394
  naming each task once. Fewer than ``LABELS_MIN_ROWS`` labelled rows are
1363
- read as classes."""
1364
- labels = [_fold_situation(r.get("situation")) for r in rows if r.get("situation")]
1395
+ read as classes. Counted over identities when *identity* is given: ten
1396
+ spellings of one situation are one class, not ten."""
1397
+ labels = [_canonical_situation(r, identity or {}) for r in rows if r.get("situation")]
1365
1398
  if len(labels) < LABELS_MIN_ROWS:
1366
1399
  return True
1367
1400
  return len(set(labels)) / len(labels) <= LABELS_MAX_DISTINCT_RATIO
1368
1401
 
1369
1402
 
1370
- #: Words that carry no class information in a situation label: what the
1371
- #: label is *of* ("ticket", "issue"), not what it is about. Dropped before
1372
- #: labels are compared, so ``card declined ticket`` and ``card declined`` are
1373
- #: one record.
1374
- _SITUATION_NOISE = frozenset({
1375
- "a", "an", "the", "of", "on", "in", "for", "with", "and", "or", "to", "at", "by",
1376
- "ticket", "tickets", "issue", "issues", "problem", "problems", "case", "cases",
1377
- "request", "requests", "task", "tasks", "failure", "failures", "error", "errors",
1378
- })
1379
-
1380
-
1381
- def _fold_situation(value: Any) -> str:
1382
- """A situation label as compared.
1383
-
1384
- Case, whitespace and punctuation are folded (``Card-Declined`` is ``card
1385
- declined``), noise words that say what a label is of rather than what it
1386
- is about are dropped (``card declined ticket``), and the words are compared
1387
- as a set (``declined card``). Nothing is stemmed: ``ios`` and ``android``,
1388
- ``ui`` and ``backend`` must stay apart, and the classes a label is meant
1389
- to separate often differ by exactly one word. Measured on the CL support
1390
- harness (2026-09-26): a model asked to label the kind of ticket wrote the
1391
- same class as ``card declined``, ``Card-Declined`` and ``declined card
1392
- ticket`` across episodes; compared as typed, the class's record split
1393
- three ways and the one-loss turn never fired.
1394
- """
1395
- text = "".join(ch if ch.isalnum() else " " for ch in str(value or "").casefold())
1396
- words = [w for w in text.split() if w not in _SITUATION_NOISE]
1397
- if not words:
1398
- # A label made only of noise words is still a label: compare it as typed.
1399
- words = text.split()
1400
- return " ".join(sorted(set(words)))
1403
+ #: The hosted second stage of situation identity, when one is installed
1404
+ #: (:func:`set_situation_resolver`): ``(folded label, canonicals) -> canonical
1405
+ #: or None``, asked only for a label the token rule joins to nothing. The
1406
+ #: open-source server runs the token rule alone.
1407
+ _situation_resolver: Any = None
1408
+
1409
+
1410
+ def set_situation_resolver(resolver: Any) -> None:
1411
+ """Install the second stage of situation identity — an alias table, an
1412
+ embedder — consulted by the priors when the token rule finds no canonical
1413
+ for a declared label. ``None`` removes it."""
1414
+ global _situation_resolver
1415
+ _situation_resolver = resolver if callable(resolver) else None
1416
+
1417
+
1418
+ def _fold_situation(value: Any, covariates: Mapping[str, Any] | None = None) -> str:
1419
+ """A situation label as stored and compared: ``amfs_core.situations.fold``.
1420
+ Case, whitespace and punctuation folded, noise words dropped, the words
1421
+ compared as a set, and the task's declared *covariates* — keys and
1422
+ values — dropped from it (``android card declined plan team`` is ``card
1423
+ declined``). Nothing is stemmed here — the fold is the record's key —
1424
+ and spellings one stem or one word apart meet in
1425
+ :func:`_situation_identity`."""
1426
+ from amfs_core.situations import fold
1427
+
1428
+ return fold(value, covariates)
1429
+
1430
+
1431
+ def _row_fold(row: Mapping[str, Any]) -> str:
1432
+ """A row's situation folded with the covariates the row recorded."""
1433
+ from amfs_core.actions import recorded_covariates
1434
+
1435
+ return _fold_situation(row.get("situation"), recorded_covariates(row))
1436
+
1437
+
1438
+ def _situation_identity(
1439
+ scanned: Sequence[Mapping[str, Any]], rows: Sequence[Mapping[str, Any]] = (),
1440
+ ) -> dict[str, str]:
1441
+ """The record's situation identity: every folded label on *scanned* (the
1442
+ entity's record, newest first) and *rows* (the neighbourhood) joined to
1443
+ its canonical — the first spelling of the situation, oldest first
1444
+ (``amfs_core.situations.canonicalize``). The hosted resolver, when one is
1445
+ installed, joins the synonyms the token rule cannot."""
1446
+ from amfs_core.actions import _as_dt
1447
+ from amfs_core.situations import canonicalize
1448
+
1449
+ def _when(r: Mapping[str, Any]) -> float:
1450
+ at = _as_dt(r.get("committed_at"))
1451
+ return at.timestamp() if at else 0.0
1452
+
1453
+ labels: list[str] = []
1454
+ for r in sorted(list(scanned) + list(rows), key=_when):
1455
+ labels.append(_row_fold(r))
1456
+ return canonicalize(labels, resolver=_situation_resolver)
1457
+
1458
+
1459
+ def _resolve_situation(declared: str, identity: Mapping[str, str]) -> str:
1460
+ """The canonical a declared (folded) label is read as under *identity*."""
1461
+ from amfs_core.situations import resolve
1462
+
1463
+ return resolve(declared, identity, resolver=_situation_resolver)
1464
+
1465
+
1466
+ def _canonical_situation(row: Mapping[str, Any], identity: Mapping[str, str]) -> str:
1467
+ """A row's situation as the record's identity reads it."""
1468
+ folded = _row_fold(row)
1469
+ return identity.get(folded, folded)
1401
1470
 
1402
1471
 
1403
1472
  def _nearby_record(
1404
- rows: list[dict[str, Any]], *, environment: Mapping[str, Any] | None = None
1473
+ rows: list[dict[str, Any]], *, environment: Mapping[str, Any] | None = None,
1474
+ identity: Mapping[str, str] | None = None,
1405
1475
  ) -> dict[str, Any]:
1406
1476
  """The neighbourhood outside the declared situation, per situation:
1407
1477
  ``{"outcomes": n, "by_situation": [{"situation", "outcomes", "tried":
@@ -1411,7 +1481,7 @@ def _nearby_record(
1411
1481
 
1412
1482
  groups: dict[str, list[dict[str, Any]]] = {}
1413
1483
  for r in rows:
1414
- groups.setdefault(_fold_situation(r.get("situation")) or "(unlabelled)", []).append(r)
1484
+ groups.setdefault(_canonical_situation(r, identity or {}) or "(unlabelled)", []).append(r)
1415
1485
 
1416
1486
  def _nearness(items: list[dict[str, Any]]) -> float:
1417
1487
  return max(float(r.get("task_similarity") or r.get("similarity") or 0.0) for r in items)
@@ -3817,6 +3887,7 @@ async def retrieve_entries(
3817
3887
  environment=environment,
3818
3888
  query_vector=priors_vec,
3819
3889
  situation=req.situation,
3890
+ covariates=req.covariates or None,
3820
3891
  )
3821
3892
  top = head[0][0] if head else None
3822
3893
  top_bd = head[0][2] if head else {}
@@ -3949,6 +4020,9 @@ async def retrieve_entries(
3949
4020
  # a record that can name a winner but is not about this kind of
3950
4021
  # task, so a shift read over it does not send the agent exploring.
3951
4022
  priors_are_local=(priors or {}).get("source") != "action_stats",
4023
+ # What this task is like, so a contested rule the situation's
4024
+ # record split on is read for this task's side.
4025
+ covariates=req.covariates or None,
3952
4026
  )
3953
4027
  if (
3954
4028
  priors is not None or recommendation is not None or shifted
@@ -5310,6 +5384,7 @@ async def commit_outcome(
5310
5384
  entity_path=req.entity_path,
5311
5385
  entity_paths=req.entity_paths,
5312
5386
  situation=req.situation[:200] if req.situation else None,
5387
+ covariates=normalize_covariates(req.covariates) or None,
5313
5388
  # Not scanned here: commit_outcome scans at trace construction, so
5314
5389
  # every caller gets it. Scanning again would be harmless but would
5315
5390
  # imply this endpoint is where the guarantee lives, which is the