Files
zeekayandHanzo Dev 1b7a28d31f planes: one assembly, one identity for an offer, and a bound nobody can spend twice
The defining failure of the last review was not in a plane. It was that there
were TWO wirings: cmd/amld assembled a Handler by hand and the tests assembled a
different one, so the record fingerprint could be a struct field the suite
exercised and no column stored — every retry a permanent 409 in production while
every test passed. api.Wire is now the only assembly. It creates every
collection, opens every shelf, makes every join and registers what has to run on
a cadence; cmd/amld supplies only what an installation answers differently, the
tests call the same function, and internal/source.NoLiteral reads cmd/amld to
refuse a second copy. Handler completeness is checked by reflection, because a
hand-written field list would be the third copy.

A retry is not a second transaction. pkg/receipt resolves the identity of an
OFFER once, at the top of ingest, before anything is read or written, and returns
the prior answer byte for byte — so the ledger, the aggregates, the history, the
alerts and the case plane all agree on one transaction instead of the ledger
holding one record while the aggregates hold three. Two different facts under one
reference is 409 and never 503. Because the answer is kept AFTER the work, a
process that dies in between leaves no receipt, so every plane past it also
recognises the transaction for itself: history does not append a second row,
alerts keep the first judgement, and a judged transaction opens no second case.

A bound over a COUNT of caller-sized values is not a bound. types.MaxIdent bounds
every identifier at the door, which is what turns the counts downstream into
figures in bytes; dictionary.MaxName does the same for a payload key, and
dictionary.Ceiling is the product a test WEIGHS a full accumulator against. The
field catalog's accumulator moves into roster, which admits and never removes, so
per-tenant bounds multiply by ONE number an operator can hold against a pod.

engine.Evaluator now keeps no compiled rules at all. A candidate's text arrives on
the wire at /v1/aml/rules/test, so a compiled-rule table there was keyed by a
string a caller wrote, sized by how many distinct ones a caller sends, with no cap
and no removal, in the memory every institution's ingest runs in — an OOM from one
authenticated caller, which on this deployment is every control off at once. A
rule's compiled form is a value with an owner: the installed library, or one
replay. Nothing shared, nothing to grow. Found here, not reported.

Handler.history is the one function that materialises a whole retained history, so
it now REQUIRES a *topology.Grant, and a Grant comes from Budget.Admit and nowhere
else. An ungated whole-history read is something a caller has to write on purpose
rather than something a new door can forget. The rule replay and the activation
rate fold take the same one budget the model studies take.

Reaching a bound is allowed; reaching it quietly is not. GET /v1/aml/load is the
one door for "is anything of mine quietly degraded": the tenant's aggregates
against its own ceiling in bytes with a grade, whether it has a behavioural model
at all, the field catalog's pressure, and the process's counts of institutions
held and refused. It names no other institution.

Closing R1-R8 from the review plus R11, the two recurring classes, and the silent
degradation the load door answers. Twenty-four mutations, twenty-four killed.

Co-authored-by: Hanzo Dev <[email protected]>
2026-08-02 11:32:15 -07:00

137 lines
4.9 KiB
Go

package history
import (
"context"
"fmt"
"time"
"github.com/hanzoai/base/core"
"github.com/hanzoai/dbx"
)
// Collection is where transaction events are stored.
const Collection = "aml_transactions"
// Store field names. They are named once here because the writer and the reader
// have to agree, and a silent disagreement produces an empty window rather than
// an error — which reads as a customer with no history.
const (
fieldUser = "user_id"
fieldAccount = "account_id"
fieldCounterparty = "counterparty"
fieldDevice = "device"
fieldAddress = "address"
fieldJurisdiction = "jurisdiction"
fieldSymbol = "symbol"
fieldDirection = "direction"
fieldCurrency = "currency"
fieldUSD = "usd"
fieldAt = "at"
fieldTxID = "tx_id"
)
// subjectField maps a subject kind to the column that identifies it.
var subjectField = map[string]string{
SubjectUser: fieldUser,
SubjectAccount: fieldAccount,
SubjectCounterparty: fieldCounterparty,
SubjectDevice: fieldDevice,
SubjectAddress: fieldAddress,
}
// Base reads event windows from a Base collection.
type Base struct{ app core.App }
// NewBase builds a Store over a Base app.
func NewBase(app core.App) *Base { return &Base{app: app} }
// Window returns the subject's events over the lookback, most recent first.
//
// The subject's identifier is bound as a parameter. Written into the filter as text
// it could change the shape of the query: an identifier containing the filter
// language's own syntax can widen the window to another tenant's transactions or
// narrow it to none, and narrowing it to none is the dangerous direction, because a
// velocity rule over an empty window reports no velocity.
//
// The window is bounded by the transaction's own timestamp, not by when the record
// was written. Those differ whenever events are replayed or backfilled, and
// aggregating a reporting period by insertion time attributes activity to the day
// the importer ran.
func (b *Base) Window(ctx context.Context, subj Subject, lookback time.Duration) ([]Event, error) {
if err := subj.Valid(); err != nil {
return nil, err
}
field := subjectField[subj.Kind]
since := time.Now().UTC().Add(-lookback)
filter := fmt.Sprintf("%s = {:id} && %s >= {:since}", field, fieldAt)
records, err := events.Find(b.app, subj.OrgID, filter, "-"+fieldAt, 0, dbx.Params{
"id": subj.ID,
"since": since,
})
if err != nil {
return nil, fmt.Errorf("history: window for %s %q: %w", subj.Kind, subj.ID, err)
}
out := make([]Event, 0, len(records))
for _, r := range records {
out = append(out, Event{
ID: r.GetString(fieldTxID),
At: r.GetDateTime(fieldAt).Time(),
USD: r.GetFloat(fieldUSD),
Currency: r.GetString(fieldCurrency),
Direction: r.GetString(fieldDirection),
User: r.GetString(fieldUser),
Counterparty: r.GetString(fieldCounterparty),
Account: r.GetString(fieldAccount),
Device: r.GetString(fieldDevice),
Address: r.GetString(fieldAddress),
Jurisdiction: r.GetString(fieldJurisdiction),
Symbol: r.GetString(fieldSymbol),
})
}
return out, nil
}
// Append records an event so it appears in later windows.
//
// USD is stored as converted at the time of the transaction. Converting on read
// instead would let a rate movement change what a past window totalled, so an
// aggregate that crossed a reporting threshold yesterday could fall below it
// today and a filed report would no longer be reproducible from the data.
// An event IS one transaction, so an id this tenant has already recorded is not
// a second event and is not appended. That matters beyond a client retry: the
// answer to an offer is kept AFTER the writes, so a process that dies between
// them leaves the work done and no record of having answered, and the client —
// never answered — offers again. Every plane the ingest path writes to has to
// recognise the transaction by itself rather than rely on being sequenced behind
// something that does, or the count every aggregate rule reads is wrong by the
// number of times the process was interrupted.
func (b *Base) Append(ctx context.Context, orgID string, e Event) error {
held, err := events.Find(b.app, orgID, fieldTxID+" = {:tx}", "", 1, dbx.Params{"tx": e.ID})
if err != nil {
return fmt.Errorf("history: %w", err)
}
if len(held) > 0 {
return nil
}
r, err := events.New(b.app, orgID)
if err != nil {
return fmt.Errorf("history: %w", err)
}
r.Set(fieldTxID, e.ID)
r.Set(fieldAt, e.At.UTC())
r.Set(fieldUSD, e.USD)
r.Set(fieldCurrency, e.Currency)
r.Set(fieldDirection, e.Direction)
r.Set(fieldCounterparty, e.Counterparty)
r.Set(fieldAccount, e.Account)
r.Set(fieldDevice, e.Device)
r.Set(fieldAddress, e.Address)
r.Set(fieldJurisdiction, e.Jurisdiction)
r.Set(fieldSymbol, e.Symbol)
r.Set(fieldUser, e.User)
return b.app.Save(r)
}