Skip to content

Latest commit

 

History

History
502 lines (366 loc) · 39.7 KB

cap-contract.md

File metadata and controls

502 lines (366 loc) · 39.7 KB

Cap contract (product-gate integrator)

Developer-facing contract for a product gate that talks to memnet-serve or the generic MCP front (memnet-mcp). Every default, refuse, clip, and wire string below was read from the engine and re-hit by tests/test_cap_contract.py / scripts/probe_cap_contract.py. Do not treat this file as doctrine SSOT for goldfish; wire SSOT remains grammar/gql-wire-profile.md.

This cut does not change any cap or behaviour. If a probe finds a silent clip or a leftover gap, it is listed as a bug for a follow-up.

Never log a session id. MCP JSON may include one; redact it at the gate.

How to read a reply

Surface Shape
Library MemNetError(code, message) then CLI format_err
CLI / serve stderr @ERR: {code}|{message} (pipes inside message become spaces). Exit 1 or 2. Mutate also prints ok=0 fail=1
MCP JSON text: exit_code, stdout, stderr, session_id, errors (each @ERR: … line). Not a Python exception to the host
Product read (pin_map) stdout may carry ## Truncation truncated=true M=… omitted=… reason=…
Honesty (not a resource cap) ## CueConflict, ## CueMiss, ## Peak_L, ## outline, ## Reserves
Advisory @WRN: (max 12 per call, then dropped) and @STAT: key|value|cap

format_err lives in memnet/output.py. MCP wraps CLI via memnet_mcp.client.MemNetResponse.

Commit gate (writes)

MutateGate (memnet/mutate_gate.py) applies a batch, then on MemNetError deletes added hids, restores replaced rows, restores deleted rows, and inverts renames. A refused write is all-or-nothing for that batch. Separate successful calls that already returned stay. Session row cap does not evict; it refuses the next new non-LAW row (nodes and edges).

Path-B ingest (PinMapIngestBase.commit) projects first; ingest_budget raises before commit. A projection that fits ingest caps can still hit MEMNET_MAX_ROWS at commit; that batch rolls back.

Integrator checklist

  1. Map @ERR: {code} to a typed error. Do not parse English prose as the stable key; code is the key, message is detail.
  2. On hard refuse: do not retry the same payload unchanged. Split the batch, raise the cap, narrow the artefact, or grant ACL/RSV.
  3. On ## Truncation: the neighbourhood is incomplete. Narrow the cue, filter, or raise max_rows / lower depth / avoid view=shell. Never treat a clipped read as complete.
  4. On leftover query walk / query context: those paths can clip without Truncation (bugs below). Prefer product pin_map. Never retry a hard refuse unchanged.
  5. At session row cap: stop inserting; housekeep or open another session. Nothing is evicted.
  6. On session_expired\|snap_missing: the graph is gone unless the operator saved. On snap_available: session_load with the known id (expire dir).
  7. Never put a session id in logs, traces, or mapped errors.

Ingest node budget

Default 2000 (DEFAULT_INGEST_MAX_NODES)
Knob CLI --max-nodes, MCP max_nodes. Not an env var
Kind Hard refuse (ingest_budget). No silent clip
Library ingest_budget / pin budget exceeded (max_nodes={N})
Wire @ERR: ingest_budget|pin budget exceeded (max_nodes={N})
MCP errors contains that line; exit_code=1
Write Project refuses before commit. Session unchanged
Gate should Split the artefact, Snap interiors, or raise --max-nodes
Gate must not Retry the same path; dump the load tree into one session

Source: memnet/pin_map_ingest.py _budget_check / SysML def loop; CLI ingest sysml; MCP ingest_sysml.

Ingest edge budget

Default 2000 (DEFAULT_INGEST_MAX_EDGES)
Knob CLI --max-edges, MCP max_edges
Kind Hard refuse
Library ingest_budget / edge budget exceeded (max_edges={N})
Wire @ERR: ingest_budget|edge budget exceeded (max_edges={N})
Write Before commit
Gate should Raise --max-edges or cut the artefact
Gate must not Retry unchanged

Source: _edge_budget_check / _budget_over.

Ingest file budget

Default 64 files (argument default, not env)
Knob --max-files / MCP max_files
Kind Hard refuse
Wire (SysML dir) @ERR: ingest_budget|too many .sysml files ({n} > max_files={N})
Also too many source files (…) / too many .ato files (…) / too many skill/rule files (…)
Gate should Point at one file or raise max_files

Source: _collect_sysml_files and cousins.

Per-session row cap (maxRows)

Default 5000 non-LAW records (nodes and edges)
Knob MEMNET_MAX_ROWS (baked into Caps at session open)
Kind Hard refuse of the next new non-LAW row. Updates of existing rows still apply. No eviction
Library limit_exceeded / rows|{n}/{max}
Wire @ERR: limit_exceeded|rows {n}/{max} (pipe in the message becomes a space)
Mutate extra ok=0 fail=1 on stderr
MCP errors: ["@ERR: limit_exceeded|rows {n}/{max}"]
Batch All-or-nothing rollback (probe: 3 CREATEs with cap 2 → 0 rows left)
In memory at cap Further CREATE refuses; existing graph stays
Per session session set-limits --max-rows N (MN-REQ-05.6) sets a tighter cap on one live session; the cap in force is min(N, MEMNET_MAX_ROWS) and the refusal names it
Gate should Housekeep, split sessions, or raise MEMNET_MAX_ROWS before open
Gate must not Retry the same CREATE; assume old rows were dropped

Source: MemStore.upsert in memnet/mem_store.py. LAW rows use max_law instead.

Near-cap advisories on session load: @WRN: near_cap at 80%, @WRN: near_cap_critical at 95% (memnet/warnings.py).

Relation-type cap (maxRelations)

Default 200 (MEMNET_MAX_RELATIONS). Not 5000
Knob MEMNET_MAX_RELATIONS
Kind Hard refuse when adding a new type with allow_new_relation=True
Library limit_exceeded / relations|{n}/{max}
Wire @ERR: limit_exceeded|relations {n}/{max}
Seed relations.seed.txt is loaded without this cap (41 types in-tree). Setting the env below seed size blocks new types only; seed types still work
Without --allow-new-relation unknown_relation instead (see below)
Gate should Reuse a seeded type, pass allow_new_relation, or raise the cap
Gate must not Retry the same new type unchanged

Source: MemStore.upsert relation branch; session._seed_relations.

Unknown relation (not a size cap)

Default Product mutate / leftover add default allow_new_relation=False
Kind Hard refuse
Wire @ERR: unknown_relation|{rel} known: {comma-list}
Gate should Use a known type or pass allow_new_relation=true

Path-B ingest commits with allow_new_relation=True.

LAW cap

Default 100
Knob MEMNET_MAX_LAW
Kind Hard refuse of a new LAW row
Wire @ERR: limit_exceeded|law {n}/{max}

Tag-map caps

Limit Default Knob Wire
User tags 64 MEMNET_MAX_TAGS @ERR: limit_exceeded|tags {n}/{max}
Fields per tag 64 MEMNET_MAX_FIELDS @ERR: limit_exceeded|fields {n}/{max}

SCHEMA register refuses a declared map over the cap (memnet/tag_map.py). Mutate uses the same cap on the effective field set: declared SCHEMA fields, plus undeclared extras on any row of that tag, plus the id column snapshot save appends. Over-cap CREATE/SET/MERGE refuses limit_exceeded|fields {n}/{max} and writes nothing. Snapshot save uses that same helper (memnet.snapshot.effective_snapshot_fields); it is never stricter than a mutate that succeeded. Snapshot load of a SCHEMA over the cap refuses the same fields {n}/{max} code. snapshot_unsaveable stays the fail-closed save backstop when RAM still exceeds the cap.

Pipe value / line bytes

Limit Default Knob Wire
Field value 32768 MEMNET_MAX_VALUE_BYTES @ERR: limit_exceeded|value_bytes|{n}/{max}
Whole pipe / snapshot line 135168 MEMNET_MAX_LINE_BYTES @ERR: limit_exceeded|line_bytes|{n}/{max}
Session total (escaped snapshot line bytes) 163840000 MEMNET_MAX_SESSION_BYTES @ERR: limit_exceeded|session_bytes|{n}/{max}

Value cap is one hard cap on leftover @TAG parse_line, GQL mutate (CREATE / SET field values), and snapshot load. It is measured as the UTF-8 byte length of the decoded (raw) property value, not the escaped wire form. Default 32768 (was 4096 before this change); a product MAY lower or raise it with MEMNET_MAX_VALUE_BYTES. Over-cap refuses limit_exceeded|value_bytes|{n}/{max} and does not store the row.

Line cap is the UTF-8 byte length of the escaped/raw leftover-pipe or snapshot line. Save verify and load share this check. The default 135168 is sized for the worst case of one value at the default value cap: snapshot emit escapes FS/GS/RS (\x1c / \x1d / \x1e, one byte each) as four bytes each (\x1c written out), so 32768 bytes of them escape to 131072, plus 4096 for tag, key and framing (4 x 32768 + 4096 = 135168). Backslash and pipe only double; LS/PS (three bytes) escape to six. If you raise the value cap, raise the line cap with it (4 x value cap + 4096). GQL statements are not pipe lines.

Mutate-time line refusal. Before a write is stored (GQL CREATE / SET / MERGE, leftover pipe), mutate first checks each value: the value cap (value_bytes|{n}/{max}) and the value's escaped wire size against max_line_bytes (memnet.wire.escaped_utf8_len). It then measures the escaped UTF-8 size of the whole record line (all fields), exactly as snapshot emit would write it, for every record as it stands after the write. If that size exceeds max_line_bytes, mutate refuses @ERR: limit_exceeded|line_bytes|{n}/{max_line} (n = whole escaped line bytes) and stores nothing; the batch stays all-or-nothing. Because mutate checks the whole line, not each value, no accepted write makes a snapshot unsaveable through line size. Save keeps its own check (snapshot_unsaveable wrapping line_bytes) as a backstop, for example after the cap is lowered.

Edge and schema lines. The same check covers every other snapshot line a write changes. Edges are records (@EDG) written with endpoint nicks, so mutate measures each written edge and every edge incident to a written or renamed node (a rename changes the nick in those edge lines). It also measures every per-tag SCHEMA line as save would emit it, including keys the write added to the schema (undeclared keys widen it, MN-REQ-01.9). Over the cap refuses limit_exceeded|line_bytes|{n}/{max_line} inside the same rollback scope, before mark_written: records, edges and schema are restored. Writers that bypass the mutate gate (snapshot import, durable hydrate, CLI delete/prune) get the same checks from memnet/bypass_caps.py; see Bypass paths below.

Tag widening. An undeclared key on one row adds a column to every row of that tag in the snapshot, and an empty column still costs one | byte. A second row with the same key adds the column again (MN-REQ-01.9). So a write can push a row it did not touch over the cap. When a write changes the columns a tag emits, mutate measures every row of that tag. If one would exceed max_line_bytes, mutate refuses @ERR: limit_exceeded|line_bytes {n}/{max_line} {TAG} nick={row} (library message line_bytes|{n}/{max_line} {TAG} nick={row}), naming the row that would overflow, and rolls the batch back. Snapshot import and CLI delete and prune run the same check. To make the write fit, shorten the named row or drop the key.

Session byte budget (MN-REQ-14.10). Each session has a total budget, default 163840000 bytes (5000 x 32768; the single constant DEFAULT_MAX_SESSION_BYTES in memnet/config.py), set by MEMNET_MAX_SESSION_BYTES. It counts the escaped snapshot line bytes (UTF-8) of every schema, record and edge line, exactly as snapshot emit writes them. That is the measure the line cap and save already use, and it is an upper bound on raw value bytes. After a write is computed, if the session total would exceed the budget, GQL CREATE / SET / MERGE and leftover pipe mutate refuse @ERR: limit_exceeded|session_bytes|{n}/{max} (n = the running total at the line where the count first passed the budget, so a lower bound of the full total) and roll back exactly like the line_bytes refusal, so the session is unchanged. Deletes are always allowed. The default is a deliberate cap, not a floor: 5000 records at the 135168-byte line cap would be 675,840,000 bytes, so the default can refuse a write that the value, line and row caps allow. A product that raises those caps should raise this budget too. There are no tombstones today, so none are counted.

Bypass paths (MN-REQ-14.11). Writers that do not go through the mutate gate enforce the same caps with the same limit_exceeded codes, and are atomic: a refused call leaves the session exactly as it was (store, relations, indexes).

Path Checks On refusal
Snapshot import (import_absorb) value cap on the incoming records; then field cap, whole-line cap (record, edge, SCHEMA) and session byte budget on the result Lead session restored; nothing imported
Ingest (ingest_*) Goes through the mutate gate, so the mutate checks apply Mutate rollback
Snapshot load Loader refusal of an over-cap value or line is kept; a snapshot whose stored SCHEMA + record lines exceed the budget is refused session_bytes No session registered
Snapshot save session_bytes is checked with the existing line verify No file written
CLI delete, housekeep prune Line cap only (see below); never the byte budget Whole delete or prune batch restored

Hydrate into an over-budget session. If the hydrated result puts the session over the budget, including a durable session that is already over a lower MEMNET_MAX_SESSION_BYTES than it was written under, the hydrate is refused @ERR: limit_exceeded|session_bytes|{n}/{max} with the example raise MEMNET_MAX_SESSION_BYTES or shrink the session. The session is left as before. It is never truncated and never partly loaded; raise the setting and hydrate again. Per-value and per-line violations refuse the same way (value_bytes, line_bytes, naming MEMNET_MAX_VALUE_BYTES / MEMNET_MAX_LINE_BYTES). Save (including save-on-expire) refuses an over-budget session the same way: the in-RAM session stays, and no file is written.

What a delete can grow. A delete shrinks the session, so the byte budget never refuses it (as with mutate deletes). Two lines can still grow: an edge whose endpoint node is deleted is written with the endpoint's longer hidden handle instead of its nick, and a SCHEMA line can change when its undeclared keys go. The rewritten edge and SCHEMA lines must still pass the line cap. If any would exceed it, the delete (or the whole prune batch) is refused line_bytes and nothing is removed.

Rollback. Older hosts keep the old defaults (value 4096, line 32768) and have no session byte budget. They refuse on load any snapshot with a value over their cap. Before loading a snapshot written under these defaults on an older host, raise MEMNET_MAX_VALUE_BYTES (to 32768) and MEMNET_MAX_LINE_BYTES (to 135168) there.

Snapshot emit escapes every Python str.splitlines() separator (LF, CR, VT, FF, FS/GS/RS, NEL, LS, PS) plus | and \. Load splits records on LF only (not str.splitlines()).

Mutate stdin, leftover pipe batches, and GQL statement breaks use that same LF-only split (one optional trailing CR is stripped). A raw VT, FF, FS, GS, RS, NEL, LS, or PS inside a value stays inside the value. It does not start another statement. An embedded CR is not a break. A raw LF still separates statements. This matches snapshot load (#202): the separator is kept literally, not refused.

Undeclared properties. GQL mutate may store keys that are absent from the live tag SCHEMA (GraphElement extras; Path-B locators such as qname). Those keys stay in RAM. Snapshot save persists them by widening the snapshot SCHEMA (live session SCHEMA is unchanged). The widen keys extras by the canonical SCHEMA tag, so a CREATE label whose spelling differs in case from the SCHEMA tag still persists. After load, the restored map includes the extra columns. Extras on fixed tags EDG / LAW refuse snapshot_unsaveable and write no file. A mutate that would widen a tag over max_fields refuses limit_exceeded|fields {n}/{max} and writes nothing. Save uses the same effective-field count; snapshot_unsaveable wrapping fields|{n}/{max} remains the backstop if RAM still exceeds the cap.

A live SCHEMA that omits id is accepted at open (id need not be present or first). Save still succeeds: the snapshot SCHEMA appends an id column and the row gets a minted nickname. The live map is unchanged until that snapshot is loaded. A property key that does not survive the SCHEMA whitespace split (for example foo bar) cannot reload, so save refuses snapshot_unsaveable and writes no file. A 64-field map with no id becomes 65 columns and refuses fields|65/64.

Labelled MATCH and edge create. MATCH (n:Label {…}) SET is intended to match. The label is case-folded to the SCHEMA tag (cst, Cst, and CST are the same tag). A label that is a different known tag and matches nothing is @ERR: not_found, not a silent success. MATCH (a) MATCH (b) CREATE (a)-[:rel]->(b) is @ERR: parse_error (unsupported MATCH continuation). The comma form MATCH (a), (b) CREATE (a)-[:rel]->(b) with --allow-new-relation creates the edge. The MATCH-MATCH form is not implemented.

Housekeep orphans (MN-REQ-04.12). GQL edges store endpoints as hidden element ids (_elN). Leftover pipe may store the nickname. Orphan, dangling, and stale counts resolve both. A node is an orphan only when no edge names it. housekeep stats on a fully linked GQL graph reports orphans 0. prune orphans and prune stale with --apply recompute and refuse @ERR: prune_referenced (nothing deleted) when a candidate node is still an endpoint. The stale_orphans warning suggests prune orphans --apply only for that true-orphan count. No sweep, expire job, or MCP tool runs prune --apply. The only caller is the CLI when a person passes --apply. housekeep_stats on MCP is read-only.

Snapshot save verifies every emitted row can parse back to the same values. If any row cannot, save refuses @ERR: snapshot_unsaveable|{tag} nick={nick} … and writes no file. Expire-save in that case (or any other save failure, such as an unwritable disk or directory) emits @WRN: expire_snapshot_failed|{code} on every sweep or access that retries expiry, writes no file, and keeps the session in RAM. It still counts against MEMNET_MAX_SESSIONS. Access after TTL is @ERR: session_expired|overdue. An explicit session save that succeeds, or an explicit session close, ends that hold. When save-on-expire is off, TTL still drops RAM. Snapshots written by 0.19.18 (pipe and backslash escapes only) still load.

Mutate batch line cap

Default 1000 raw lines
Knob MEMNET_MAX_BATCH_LINES
Kind Hard refuse before sanitise / commit
Wire @ERR: limit_exceeded|batch_lines {n}/{max}
Gate should Split the stdin batch

Source: cli._read_ingest_input.

pin_map row clip (M)

Default 50 (DEFAULT_QUERY_MAX_ROWS)
Knob CLI --max-rows, MCP max_rows. Not MEMNET_MAX_ROWS
Kind Signalled clip
Wire ## Truncation truncated=true M={max_rows} omitted={n} reason=max_rows
Fit Mark omitted when the offer fits
Gate should Narrow cue / filter / raise max_rows
Gate must not Treat the emit as complete

Source: MemStore.context_pack + PinMapComposer.emit_truncation.

Empty cue is session outline (OUTLINE_EXEMPLAR_LIMIT=3 per kind, still one max_rows). Clip uses the same Truncation mark (reason=max_rows).

pin_map hop depth

Request default 2 (DEFAULT_QUERY_DEPTH, --depth)
Hard ceiling 4 (MEMNET_MAX_DEPTH)
Kind Signalled clip: depth = min(requested, max_depth) plus Truncation reason=depth
Wire example ## Truncation truncated=true M=50 omitted=0 reason=depth
Gate should Stay within 4 or raise MEMNET_MAX_DEPTH on the process

pin_map fan-out

Default 256 (MEMNET_MAX_FANOUT)
Kind Signalled clip (reason=fanout) plus @WRN: fanout_clamped on the store path
Wire Truncation reason=fanout (may combine with max_rows as reason=max_rows,fanout)
Gap Clamp applies to outgoing _edges_from only, not inbound _edges_to (bug list)

view=shell grain

Default Off. Soft caps SHELL_MAX_NODES=8, SHELL_MAX_EDGES=12
Kind Signalled clip reason=shell
view=interior No extra soft cap
Unknown view Hard refuse @ERR: bad_view|unknown view=…

leftover query walk

Default --max-rows=50, --depth=2, then min(depth, max_depth)
Kind Silent clip of hop list (bug). No Truncation, no @ERR
Wire @WALK: src -[rel]-> dst lines only, truncated to max_rows
Fan-out Also silent in context_walk_hops
Gate must Not use this as product read. Use pin_map

leftover query context

Kind Silent clip: context_pack(..., clip_notes=None) slices [:max_rows] with no Truncation
Gate must Use query pin-map / MCP pin_map

leftover query neighbors / query path

Neighbors Depth silently min'd to max_depth. Fan-out may @WRN: fanout_clamped without Truncation
Path find_path walks at max_depth and may return empty with no mark

find LIMIT

Default No default — --limit required (no_limit)
Kind Honesty, not a resource cap. total > 1 → ## CueConflict |Q|={total}
Listed seeds hits[:limit]; cardinality is the true hit count
Gate must not Pick one root. Tighten locators

bad_limit when --limit < 1.

Concurrent sessions

Default 1024
Knob MEMNET_MAX_SESSIONS
Kind Hard refuse of session open
Wire @ERR: limit_exceeded|sessions {n}/{max}
List @STAT: sessions|{n}/{max}
Gate should Close unused sessions

Model Snap (snap_model) session cost

Catalog Snap is 1 catalog + N interiors for one load tree. N is the number of top-level packages, plus at most a few kind-band or nested-package cuts when a package exceeds about (2M) ((M=50), so about 100 pins). Never one session per part or requirement. Default caps are unchanged (MEMNET_MAX_SESSIONS=1024, ingest max_nodes=2000, max_edges=2000). Client wait for a serve/IPC reply stays 30 s (SERVE_CLIENT_TIMEOUT_S); that is a client wait, not a resource cap.

Session cost 1 catalog + N package interiors (kind-band / nested package only when over ~2M and the cut is not a single leaf)
Mid-size model A few hundred parts and requirements in two packages → 3 live sessions
Pre-check Before mint: 1+N against remaining session slots; each interior against max_nodes / max_edges
Session refuse @ERR: limit_exceeded|sessions {n}/{max} — nothing created
Ingest refuse @ERR: ingest_budget|pin budget exceeded (max_nodes={N}) (or edge) — nothing created
Mid-way failure All sessions this call minted are closed
Repeat same root Replace: new stack commits, then the previous stack for that resolved root is closed. Live count does not double. Needs headroom for the new stack while the old one is still live
Client wait exceeded @ERR: serve_timeout|wait exceeded (exit 1). Serve stops Snap and rolls back (caller_gone)
Caller socket gone Serve-side @ERR: caller_gone|snap_model stopped; sessions rolled back if the peer is still there to read it
Gate should On refuse, do not retry the same payload unchanged. Close unused strata before Snap if the registry is near cap
Gate must not Treat a serve_timeout as “Snap is still running for us”. After timeout the serve rolls back or the retry replaces

Source: memnet/catalog_snap.py snap_model / _precheck_plan; memnet/serve.py SERVE_CLIENT_TIMEOUT_S.

Session TTL and expiry

Default TTL 60 minutes (MEMNET_SESSION_TTL_MINUTES). Open --ttl / MCP ttl
Legal range 1..1440 else @ERR: bad_ttl|ttl must be 1..1440
Live access Sliding TTL: each get_session extends expires_at by the original minutes
Unit Minutes, not seconds. --ttl 60 is 60 minutes. 130 s idle is inside that window
Sweep No background timer. purge_expired runs on access (get_session, open, list, count, save, close). A successful access slides expires_at forward by another ttl_minutes. After real expiry, access refuses session_expired (snap_missing, or overdue when expire-save kept RAM)
Expire, save off (default) Session dropped from memory. First access of the still-registered expired id: @ERR: session_expired|snap_missing (exit 2). After purge already ran: @ERR: session_not_found|unknown session
Expire, MEMNET_SAVE_ON_EXPIRE truthy + MEMNET_EXPIRE_SNAPSHOT_DIR set Snapshot {dir}/{sid}.snap (filename only; do not log it). Next use: @ERR: session_expired|snap_available. Restore: session_load with that id
Save-on-expire on, dir unset @WRN: save_on_expire_no_dir|dir unset, then drop; snap_missing
Save-on-expire on, row not round-trippable or write fails @WRN: expire_snapshot_failed|{code}, no file, RAM stays; access @ERR: session_expired|overdue. Still counts against MEMNET_MAX_SESSIONS. Cleared by a successful explicit session save or session close
session save after TTL with save-on-expire Allowed; @WRN: session_expired_saved. Id then gone
session save after TTL with save off @ERR: session_expired / snap_missing; no file
Unsaveable explicit save @ERR: snapshot_unsaveable|{tag} nick={nick} …; no file; overdue hold stays if expire-save had already failed
Status (no paths, no ids) @STAT: save_on_expire|0| / 1; @STAT: expire_snapshot_dir_set|0| / 1; @STAT: expire_snapshot_failed|n|

Source: memnet/session.py, memnet/config.py save_on_expire / expire_snapshot_dir.

Unsaved expiry: the in-memory graph is gone. There is no recycle of rows into another session.

Live session limits (MN-REQ-05.6)

Read memnet session limits --session S [--caller C] / MCP session_limits. READ (replayed after a reset); a touch
Change memnet session set-limits --session S [--ttl N] [--max-rows N|default] [--max-bytes N|default] [--caller C] / MCP session_set_limits. WRITE (never replayed; refused serve_draining while draining)
Reply @STAT: ttl_minutes|N|session, @STAT: expires_at|ISO|-, @STAT: max_rows|N|session or process, @STAT: max_session_bytes|N|session or process, @STAT: rows|n|max, @STAT: session_bytes|n|max (- when not exactly countable)
Cap in force min(override, process cap). An override only tightens; default clears it. Above the process cap: @ERR: bad_limit|max_rows must be 1..5000 (or max_session_bytes must be 1..163840000; the number is the serve cap)
Below usage @ERR: limit_below_usage|rows {n}/{cap} or session_bytes {n}/{cap}. Nothing changes; rows are never dropped. Prune first. A cap equal to usage is allowed (the session is then at its cap)
TTL 1..1440 else @ERR: bad_ttl|ttl must be 1..1440. The clock restarts at the call (expires_at = now + ttl); later slides use the new TTL. An already overdue session gets the usual expiry codes
Nothing given @ERR: no_limit|give --ttl, --max-rows or --max-bytes
All or nothing Every argument is checked first; any refusal leaves TTL and caps unchanged
Who ACL off: whoever holds the id (as session close). ACL on: set-limits needs the mutate grant, limits needs pin_map (acl_who / acl_denied / acl_forbidden)
Persisted TTL in @SNAP field 4. Overrides in one #@LIM: {"max_rows":N,"max_session_bytes":N} header line, only when set (session save, checkpoint, upgrade-prepare, expire-save and cap-eviction). Malformed: @ERR: bad_snapshot|malformed LIM line. Above the loading serve cap: clamped, @WRN: limit_clamped|max_rows {n}/{cap}
Rollback 0.20.8 skips the # line and loads with its process caps; rows and TTL are kept, only the tighter cap is forgotten

Source: set_session_limits in memnet/session.py, #@LIM: in memnet/snapshot.py. Tests: tests/test_session_live_limits.py.

CapsPolicy ACL

Off until session acl-enable, a grant/bind (which enables), or MEMNET_ACL=1 on newly opened sessions.

Code When Wire
acl_who ACL on, no --caller / MEMNET_CALLER @ERR: acl_who|caller id required when session ACL is enabled|pass --caller or MEMNET_CALLER
acl_denied Unknown caller @ERR: acl_denied|unknown caller for this session|grant caller via session acl-grant
acl_forbidden Caller lacks pin_map or mutate @ERR: acl_forbidden|caller lacks pin_map (TRAVERSE/MATCH read) permission or … lacks mutate (WRITE) permission
acl_bind Bind set, mission/lease mismatch, require_bind=True @ERR: acl_bind|mission_id and lease must match session bind|pass --mission-id and --lease matching session acl-bind
acl_scope WorkerWriteScope miss @ERR: acl_scope|id/label outside WorkerWriteScope (GRANT) or edge outside …
acl_bad_caller / acl_bad_bind / acl_bad_scope Malformed grant/bind/scope matching @ERR:

When session ACL is enabled, session save / session load (into that ACL'd session) / session close accept --caller / MEMNET_CALLER and enforce acl_who / acl_denied / acl_forbidden (save and load use pin_map; close uses mutate). MCP session_save / session_load / session_close pass caller through. Without ACL, behaviour is unchanged.

Bind is skipped when require_bind=False and the trusted path is on (MEMNET_SERVE_INTERNAL or MEMNET_TEST_INLINE or MEMNET_ACL_SKIP_BIND). memnet serve sets MEMNET_SERVE_INTERNAL=1, so CLI/MCP through serve does not enforce bind today (who and scope still do). Library MutateGate.apply(..., require_bind=True) still refuses. Listed as a bug; not fixed in this run.

In-scope writes from earlier batches stay; a later out-of-scope batch is refused (not a partial of that batch).

Neighbourhood reserve (RSV)

Code Wire / meaning
reserve_conflict @ERR: reserve_conflict|neighbourhood already held by llm_id=… anchor=…
reserved Mutate touching another holder's ids
no_llm_id Reserve/extend/release/mutate-under-lease without llm_id
reserve_mismatch extend/release holder mismatch
reserve_expired Lease gone; treat as free
bad_ttl RSV ttl_s must be 1..86400 (default 120)

Pin-map may add ## Reserves (not a clip). Gate should wait or use the holder llm_id. Do not retry a reserve_conflict unchanged.

Import slice budget

Default max_rows × anchors with max_rows default 50
Kind Hard refuse slice_budget if len(records) > budget
Reachability Product pin_map already clips each anchor to max_rows, so the union cannot exceed the budget. Probe: export succeeds; the refuse is retained in code

Serve / IPC frame

Default 4 MiB (MEMNET_SERVE_MAX_FRAME_BYTES)
Client request over cap @ERR: frame_too_large|request payload {n} bytes exceeds cap {max} (no TCP connect)
Server request over cap @ERR: frame_too_large|request frame {n} bytes exceeds cap {max}
Response over cap Python ConnectionError (not @ERR)
Bind Non-loopback without MEMNET_SERVE_ALLOW_REMOTE raises ServeBindError (process start, not session wire)

MCP TCP with serve down: @ERR: serve_required\|run memnet serve in another terminal first (exit_code=2). Default MCP is in-process and does not need serve.

Warning budget

Default 12 @WRN lines per call (MAX_WRN_PER_CALL)
Kind Further warnings dropped with no mark (bug-class silent clip of diagnostics)

Lock timeout

Default 2000 ms (MEMNET_LOCK_TIMEOUT_MS)
Kind Configured, not enforced. SessionStore.lock is threading.RLock() with no timeout

Durable hydrate / flush (cabinet, not the live gate)

SessionLifecycle.hydrate_from_durable / flush_to_durable default max_nodes=50, max_edges=100 and the adapter slices the payload (nodes[:max_nodes]). That is a silent cabinet clip, not pin_map Truncation. A product gate using only serve/MCP ingest + pin_map does not hit it.


Session already at the row cap

After many mutates, row_count_non_law() == max_rows:

  • Next new node or edge → @ERR: limit_exceeded|rows {max+1}/{max}
  • Existing rows remain; nothing is evicted or recycled automatically
  • SET / replace of an existing hid still works
  • Housekeep prune is an explicit operator action

Session expires unsaved

Default MEMNET_SAVE_ON_EXPIRE is off. At TTL:

  1. purge_expired / next access drops the registry entry
  2. Memory graph is gone
  3. Caller sees @ERR: session_expired|snap_missing (or session_not_found if the id was never known)
  4. No snapshot file unless save-on-expire and a dir were armed before expiry

MATCH WHERE (honour or refuse)

GQL MATCH … WHERE … SET / DELETE SHALL honour the WHERE predicate. Honoured forms: true / false, property equality / <> / !=, CONTAINS, STARTS WITH, ENDS WITH, =~, 'k' IN n.list, range < / > / <= / >= (MN-REQ-14.1), and AND / OR / NOT of those. Property-map equality in MATCH still filters. MATCH (n WHERE true)-[r {id}]->() DELETE r remains the gated edge-delete spelling.

Range WHERE (MN-REQ-14.1). n.k < v, n.k > v, n.k <= v, n.k >= v on node patterns (WHERE or inline (n:T WHERE …)) and on relationship patterns (MATCH ()-[r:T]-() WHERE r.k > v SET … / DELETE r). Typing rules:

  • Range on id (n.id < v, r.id >= v, …) refuses WHERE <op> on id is not honoured at parse time, anywhere under AND / OR / NOT, number or string operand: an id is opaque identity, with no meaning from its value, order or sequence. = / <> / != on id stay honoured.
  • The right operand is a number literal (-?\d+(\.\d+)?) or a quoted string. Anything else (a property, $param, a bare word, true / false / null, a list or a map) refuses WHERE <op> operand is not honoured; a literal on the left (5 < n.x) refuses too.
  • A field is numeric iff it fully matches -?\d+(\.\d+)?([eE][+-]?\d+)?. A number literal compares numerically with a numeric field; a quoted string compares by code point with a non-numeric field.
  • Bare $name parameter refused (parameter_unsupported, parse time): a $ident in a property map, SET, or honoured WHERE value (equality and the other _parse_value operators, including query typed-walk --where) refuses @ERR: parameter_unsupported|parameter $name is not supported; write the value as a literal and writes nothing. There is no parameter binding. Quoted '$name' is a string. Existing rows that hold the literal text $name still load, match when quoted, patch, and round-trip. A range RHS $param stays unsupported_predicate (MN-REQ-14.1 rule 2).
  • Quoted number refused (where_type_mismatch, parse time, whatever the data): a quoted operand whose text fully matches the numeric pattern ('123', '000123', '-2.5', '1e3') refuses @ERR: where_type_mismatch|WHERE <op> on <var>.<key>: quoted number '<lit>'; use a number literal. The id check runs first, so a range on id stays unsupported_predicate. '' and ' 5' do not match the pattern and stay strings.
  • Stored number vs quoted string refused (where_type_mismatch, evaluation): a quoted string against a field that is numeric (non-finite 1e999 included) refuses @ERR: where_type_mismatch|WHERE <op> on <var>.<key>: stored number vs quoted string; use a number literal. One such row refuses the whole statement. AND / OR evaluate every child before combining, so the refusal does not depend on sibling order (results are otherwise unchanged).
  • No match (UNKNOWN, never an error): a missing or empty field; a number literal against a non-numeric field ('abc', '-', 'NaN', ' 5'); a numeric-looking field whose value is not finite (1e999) against a number literal. NOT of UNKNOWN stays UNKNOWN; AND / OR are three-valued; UNKNOWN at the top is no match.
  • Equality is exact text, not numeric: n.rowRev = 124 does not match '000124'; use n.rowRev = '000124' or a range (n.rowRev >= 124). <> / != compare exact text too.
  • Cardinality is unchanged: node SET / DELETE and relationship DELETE need exactly one match (0 → not_found, >1 → cue_conflict); relationship SET updates every match. A relationship WHERE names only the relationship variable (end-node predicates refuse unsupported_predicate). Any refusal leaves the session unchanged. MATCH … WHERE … RETURN stays product_gate.

If lowering cannot honour the predicate, the whole statement refuses and applies nothing:

@ERR: unsupported_predicate|WHERE {name} is not honoured

A bare $name parameter also applies nothing (mutate CREATE / SET / MERGE / DELETE and query typed-walk --where):

@ERR: parameter_unsupported|parameter $name is not supported; write the value as a literal

A range type refusal also applies nothing (mutate SET / DELETE and query typed-walk --where):

@ERR: where_type_mismatch|WHERE {op} on {var}.{key}: quoted number '{lit}'; use a number literal @ERR: where_type_mismatch|WHERE {op} on {var}.{key}: stored number vs quoted string; use a number literal

Bugs found this run (do not fix here)

  1. leftover query walk (WalkQuery / context_walk_hops): clips hops at max_rows and fan-out without Truncation/@ERR.
  2. leftover query context: context_pack without clip_notes slices max_rows silently.
  3. leftover query neighbors / query path: depth min without Truncation; path may return empty.
  4. MEMNET_LOCK_TIMEOUT_MS is stored on Caps and never applied.
  5. @WRN budget: lines after 12 vanish with no mark.
  6. Serve bind skip: memnet serve sets MEMNET_SERVE_INTERNAL=1, so session bind is not enforced on the TCP/IPC product path (who/scope are). Library require_bind=True still refuses.
  7. Serve response frame over cap raises ConnectionError rather than @ERR: frame_too_large.
  8. max_fanout clamps only outgoing _edges_from, not inbound _edges_to, so a high in-degree hub is not Truncation-marked for fan-out.

Product pin_map Truncation for max_rows / depth / fanout / shell is signalled. Mutate/ingest row-cap batches do roll back.

Proof

Live output: scripts/probe_cap_contract.py (sid-free log) and tests/test_cap_contract.py. The test file asserts the strings in the tables above so this document cannot drift without CI failing.

Admin usage report (owner / admin MCP)

Hard refusals and Truncation above are what a product gate maps for agents. The owner look at live sessions, RSS, configured caps, and those same refuse/clip counts is a separate, read-only, admin-only serve command: operations/admin-usage-report.md (MN-REQ-06.11). It is not on the agent MCP tool list. It never emits a real session id. Unset MEMNET_ADMIN_TOKEN refuses with @ERR: admin_unconfigured and no report body.

Call: memnet admin usage-report --token … via the existing serve envelope, or { "admin_usage": true, "admin_token": "…" }.