Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions .claude/skills/go/store.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Use these names, with the customer first after `ctx` for every tenant-scoped mod
| `Delete(ctx, customerID, id)` | Removes one row; `ErrNoX` when absent. |

A state change that is more than a column write gets a domain verb on the same repository:
`Calls.Finish`, `CampaignContacts.Lease`, `Episodes.Close`. Batch versions take a slice
`Calls.Finish`, `CampaignContacts.Claim`, `Episodes.CloseIdle`. Batch versions take a slice
(`InsertMany`, `GetMany`) and run one statement, never a loop of single ones.

## Validation
Expand Down Expand Up @@ -93,10 +93,12 @@ A state change that is more than a column write gets a domain verb on the same r
- Opening the database with `bun.WithDiscardUnknownColumns()` means a release that does not
know a new column still reads the row. So add a column to the table that owns it, nullable
or with a default; do not create a 1:1 side table to dodge a rollback.
- Remove a column over two releases. First stop writing it and take it out of the model:
routers of the release before still name it in their SQL. Drop it in the next release.
- A table of work routers claim (inbound messages, deliveries, jobs) is a `queue`
(`queue.go`): `claim` leases due rows with `FOR UPDATE SKIP LOCKED` in one query,
`nextDue` says when to look again, and every write after the claim goes through `heldBy`,
so a claim whose lease ran out cannot overwrite the next one. `image_jobs.go` is the
so a claim whose lease ran out cannot overwrite the next one. `image_job.go` is the
example. Do not write the claim by hand.
- Every serving connection runs with `statement_timeout` 8s, `lock_timeout` 3s,
`idle_in_transaction_session_timeout` 30s and `timezone` UTC (`sessionDefaults` in
Expand All @@ -113,6 +115,8 @@ A state change that is more than a column write gets a domain verb on the same r
- A lease is `lease_until` and `leased_by`. A queue row retries with `attempts` and
`next_attempt_at`. A sealed secret column ends in `_sealed` with its key version in
`<column>_kek_version` (`kek_version` when the table has one secret).
- `created_at` and `updated_at` are records for people: a table keeps them even when no code
reads them.

## Adding a model

Expand Down
2 changes: 1 addition & 1 deletion .claude/skills/pagination/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ type SessionPosition struct {
}
```

Store, in `QuerySessions`:
Store, in `Sessions.Select`:

```go
if after := filter.Cursor; after != nil {
Expand Down
2 changes: 1 addition & 1 deletion .claude/skills/telnyx/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ ticket comments (AI-1842, AI-1843).
- **The sandbox gate** (`dlc.Gate`) can hold back a text or a reply on a line that is not
registered for 10DLC. A text it refuses reaches no agent.
- **A webhook older than 5 minutes is refused** (`Telnyx-Timestamp`, `max_age: 5m` in the
manifest). Telnyx may send a webhook twice. The bridge claims each message once (`store.ClaimChannelThreadMessage`), so a retried delivery is dropped.
manifest). Telnyx may send a webhook twice. The bridge claims each message once (`store.ChannelThreadMessages.Claim`), so a retried delivery is dropped.
- **The line's current binding answers.** A text on an existing thread is answered by the
config bound to the line now, the same one the bridge picks (oldest binding first). The
history stays in the thread channel, so a newly bound config sees the earlier messages.
Expand Down
4 changes: 0 additions & 4 deletions .factory/features/app_store.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,6 @@ The authenticator, `policy.Enforcer`, `api.Server`, `session.Manager` and the vo
resolver and service all read through it. A deployment with no Redis address, or one whose
Redis is unreachable, reads Postgres and nothing fails.

`TouchAPIKey` is throttled per process as well. The store already refused to write
`last_used_at` more than once a minute, but it took a query to find that out, which on a
busy key was a second round trip per request for a column nothing reads in anger.

## Tracing, which is how it was measured

[internal/tracing](../../acceleration/internal/tracing) is `go.opentelemetry.io/otel` with
Expand Down
3 changes: 1 addition & 2 deletions .factory/features/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,8 +202,7 @@ The rest of the credential's shape is borrowed rather than invented. `vak_live_
config is visible as one, and the key id ends in a CRC32 so a truncated paste is rejected
before the database is asked. `last4` is all the dashboard would ever show of a secret
again. A revoked key keeps its row, because a year of request rows pointing at a deleted key
is unattributable noise, and `last_used_at` is written at most once a minute per key, since
a synchronous update would double the writes of a busy one.
is unattributable noise.

## Not done

Expand Down
46 changes: 15 additions & 31 deletions acceleration/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -567,11 +567,9 @@ must have a limit to be granted (404 `no_limit`), and an organization has at mos
grants, a used-up one not counted (409 `too_many_grants`). `getLimitUsage` lists the subject's live grants and says, per window, when
its work runs on one.

The organization and app budgets that policies held moved into this table with the migration
`20261112120000_limits`: each became the organization's or the app's own limit on its interval,
an app's under the organization it was last seen in, or under itself when it was seen in none.
The migration stops while an hourly budget exists, since limits have no hourly interval. Coming
down puts one budget back into each policy from its scope's own limits.
The organization and app budgets that policies held moved into this table: each became the
organization's or the app's own limit on its interval, an app's under the organization it was
last seen in, or under itself when it was seen in none.

### The account, its credit and its teams

Expand Down Expand Up @@ -993,8 +991,8 @@ An agent's work is done in one region, `us` or `eu` for now, and never in anothe
its sessions route to, its knowledge base and its sandbox. The region is the agent's own.
`agent.yaml` names it as `region` (the sync's `region`), as a config written with the API does
(`AgentConfigRequest.region`, `AgentConfigPatch.region`), and it is stored in
`agent_configs.region` (migration `20261202135000_agent_region`, which puts every agent before it
in `us`). An agent that names none is in `us` (`pricing.DefaultRegion`), and a sync, an update or a
`agent_configs.region` (an agent stored before the column existed is in `us`). An agent that
names none is in `us` (`pricing.DefaultRegion`), and a sync, an update or a
patch that leaves it out keeps the stored one. A region is a letter and up to 31 of a-z, 0-9 and
hyphens (`pricing.ValidRegion`).

Expand Down Expand Up @@ -1080,8 +1078,8 @@ Knowledge and sandboxes are not routed, so they are done in the work's region

- **Knowledge.** One turbopuffer backend per region `knowledge.regions` maps
(`ROUTER_KNOWLEDGE_REGIONS`), `us` always among them as before. A knowledge base stays in the
region of its first write through the router, recorded in `knowledge_namespaces` (migration
`20261202125000_knowledge_region`, which records every existing base as `us`). Work naming a
region of its first write through the router, recorded in `knowledge_namespaces` (a base from
before regions is recorded as `us`). Work naming a
region, an agent's, reads and writes a base kept there, makes one nothing was written to
there, and is refused one kept in another rather than having it moved. Work naming none, as
the knowledge API's (`/v1/agents/knowledge`) and a page's read, goes where the base is kept,
Expand Down Expand Up @@ -1111,7 +1109,7 @@ vendor the deployment routes whose factory builds with an instance's own key
and for `daytona`; any other is a 400 `provider_takes_no_key` naming the ones that are. Only a key
is taken, never an endpoint: the deployment's own is used.

Keys are kept in `provider_keys` (migration `20261202130000_provider_keys`), sealed with the
Keys are kept in `provider_keys`, sealed with the
deployment's keyring (`auth.Sealer`, as the other customer secrets are) and bound to the customer,
the vendor and the region, so a sealed key copied to another row does not open. A key is never
returned, logged or put in an error: the API lists its last four characters (`key_hint`, empty for a
Expand Down Expand Up @@ -2227,7 +2225,7 @@ from the hour `since` falls in, one item per leg with `turns` and the `p50_ms`,
The endpoint sums the rows of the organization's current apps, including rows the sweeper has
not processed yet, while the cost-anomaly check sums `requests.organization_id` over swept
billable rows, so the two can disagree for two reasons. One is an app that moved organization
within the window. The other is rows the sweeper has not yet given an organization: `MeterUses`
within the window. The other is rows the sweeper has not yet given an organization: `Spend.Meters`
reads an org's apps with no organization filter, while the cost-anomaly check skips rows with an
empty `organization_id`.

Expand Down Expand Up @@ -2526,26 +2524,12 @@ a vendor quotes outright, such as a number's monthly rental, is charged at that
same factor, which no entry stores; its `base_cost_micros` is the vendor's amount, or 0 with the
fee charged for a BYOK item.

Migration `20261118120000_price_entry_prices` stored every existing entry's price as what it
was charged: its rates times its own markup, else the list's in force when it is (or was), and
gave every item its SKU. Migration `20261130120000_drop_price_markup` then drops the
`markup_bps` those markups were kept in, on `price_changes` and `price_entries`, which nothing
had read since.

Migration `20261202120000_price_entry_region` renames `price_entries` to `price_list_entries`
and adds `region` and `byok`: every existing entry is `us` and not BYOK, and `region` keeps no
default, so every later insert names one. It ends every existing SKU in `-us`
(`llm-openai-a` becomes `llm-openai-a-us`, `llm-openai-gpt-4-1-2` becomes
`llm-openai-gpt-4-1-2-us`), and indexes items by region and BYOK state as well. `requests.sku`
and the usage ledger are not rewritten: a row keeps the SKU it was billed under, so a row priced
before the migration names its item's SKU without the region. The rename is what keeps a router
built before it from reading a BYOK entry as its item's newest price: that router's reads and
writes of the price list fail, and it keeps pricing with the list it holds in memory, reading
again every 30 seconds, until it is replaced. The first start after the migration writes one
`release` change holding only the BYOK twins the files now have, at the fee; every US item keeps
its price and its SKU. Down takes the region off the SKUs, drops the columns and renames the
table back, and refuses a list that holds a BYOK or non-US entry, which a router built before
it would read as a US price.
An entry from before prices were stored holds what it was charged: its rates times its own
markup, else the list's in force then. An entry from before regions is `us` and not BYOK, and
its SKU ends in `-us` (`llm-openai-a` became `llm-openai-a-us`). `region` has no default, so
every insert names one. `requests.sku` and the usage ledger were not rewritten: a row keeps the
SKU it was billed under, so a row priced before regions names its item's SKU without the
region.

| Command | What it does |
| --- | --- |
Expand Down
2 changes: 1 addition & 1 deletion acceleration/cmd/router/usage_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ func (s *UsageCommandsSuite) states() map[uuid.UUID]shipState {

// rowsOfEveryKind writes, started ten minutes ago, a row the usage service has, one it refused,
// one written before the router shipped, and one a data move carried in, which arrives as the
// import writes it (see TestAnImportedRequestKeepsItsUsageIDAndIsNeverShipped).
// import writes it.
func (s *UsageCommandsSuite) rowsOfEveryKind() (shipped, rejected, beforeShipping, imported uuid.UUID) {
shippedAt := time.Now().UTC().Add(-5 * time.Minute)
shipped = s.recorded(10*time.Minute, func(request *store.Request) { request.ShippedAt = &shippedAt })
Expand Down
2 changes: 1 addition & 1 deletion acceleration/docs/stream-tenancy.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ App mode needs Postgres, a keyring (`ROUTER_AUTH_KEK_V<n>_WRAPPED` with `ROUTER_
- **Floor.** An organisation can require its apps' own Stream app (`router stream-apps require`).
- **Operator CLI:** `router stream-apps require|legacy|fallbacks|backfill-pins`.

Apps that registered their keys before forwarded tokens were given a placeholder token row by migration `20261022120000`, so their background work asks the gateway for a token rather than waiting for their next request. Migration `20261023120000` then dropped the old `stream_apps` and `stream_app_keys` tables.
Apps that registered their keys before forwarded tokens were given a placeholder token row, so their background work asks the gateway for a token rather than waiting for their next request. The old `stream_apps` and `stream_app_keys` tables were then dropped.

## Testing

Expand Down
2 changes: 1 addition & 1 deletion acceleration/internal/activity/activity.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Package activity counts the requests each app makes, by area of the API and by client, and
// writes the sums to customer_activity (store.RecordActivity).
// writes the sums to customer_activity (store.Activities.Add).
//
// Every authenticated request is one, and so is a hook checked as an app's (NoteCustomer), and
// the work the router does for an app on its own: a forward to its endpoint, a scheduled task's
Expand Down
2 changes: 1 addition & 1 deletion acceleration/internal/agent/approval.go
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ func (a *Agent) approvedName(call llm.ToolCall) string {
return call.Name
}

// runningAs is the call a running call's id is held under: an approved call runs under the
// runningAsLocked is the call a running call's id is held under: an approved call runs under the
// confirmation that ran it, which is the call the model has open. The caller holds the lock.
func (a *Agent) runningAsLocked(id string) string {
if run, ok := a.approvedRuns[id]; ok {
Expand Down
2 changes: 1 addition & 1 deletion acceleration/internal/agent/ids.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ func fromNote(text string) bool {

// A name field can identify a place or business, not just a person. The lexical
// heuristics must not reject a name the caller or a successful tool already gave. A tool that
// reads back what the agent wrote with the name in it does not give it (ownLines.readBack).
// reads back what the agent wrote with the name in it does not give it (heldLines.readBack).
func nameWasGiven(history []llm.Message, name string) bool {
words := func(text string) string {
return " " + strings.ToLower(strings.Join(strings.FieldsFunc(text, func(r rune) bool {
Expand Down
2 changes: 1 addition & 1 deletion acceleration/internal/api/audit.go
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ var auditBookkeeping = []string{"id", "created_at", "updated_at", "sync_hash"}
// auditDiff is the fields that moved between two renderings of a resource.
//
// It compares the API's own shape of the thing rather than the stored row, so what a change
// names is what a client reads the resource by: `tools`, not `progressive_tools`. A field
// names is what a client reads the resource by: `tools`, not `tool_groups`. A field
// absent from one side and present on the other has moved, which is what makes a create
// every field at once and a delete every field back to nothing.
func auditDiff(before, after any) []store.AuditChange {
Expand Down
2 changes: 1 addition & 1 deletion acceleration/internal/api/authorizations.go
Original file line number Diff line number Diff line change
Expand Up @@ -724,7 +724,7 @@ func (s *Server) handOffConnectorLaunch(w http.ResponseWriter, r *http.Request)
// 2. the browser holds that attempt's cookie (RFC 6749 section 10.12, RFC 9700 section
// 2.1: the state is bound to the user agent), so a callback in another browser is
// refused and the right browser can still finish;
// 3. the attempt is used up, once (store.ConsumeConnectorAuthorizationAttempt), so a
// 3. the attempt is used up, once (store.ConnectorAuthorizationAttempts.Consume), so a
// replayed callback never reaches the provider again;
// 4. the manifest's before_complete hook sees the whole callback;
// 5. Scheme.Complete checks state, iss (RFC 9207 section 2.4) and the provider's error
Expand Down
2 changes: 1 addition & 1 deletion acceleration/internal/api/chat_channels.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (
"github.com/GetStream/Vision-Agents/acceleration/internal/store"
)

// A channel of a type an agent config names (store.AgentConfig.ChatChannels), such as a team's
// A channel of a type an agent config names (store.AgentConfig.Channels.Chat), such as a team's
// group channel, is answered by the Router itself, as a thread channel is:
//
// message.new, no source, in callouts:team-1 receiveMessageEvent, receiveChatInbound
Expand Down
4 changes: 2 additions & 2 deletions acceleration/internal/api/chat_episodes.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const chatCardTimeout = 30 * time.Second
// on or record (Spec.WritesCards), has any: off, nothing here reads or writes. A thread channel's episode is the channel bridge's, an
// omni-channel is where cards are written and never where an episode starts, and a session on
// a call has its call's card, whose lines a chat episode in the same channel would cut short
// (store.EpisodeCards, until).
// (store.Episodes.Cards, until).
//
// The episode is the person's only in a channel whose members are that person alone, or that
// person and the agent, the Stream user the agent writes its replies as: its agent id, which is
Expand All @@ -40,7 +40,7 @@ const chatCardTimeout = 30 * time.Second
//
// Every message calls Open, which keeps the episode open (episodes.last_message_at).
// A message delivered again, by Stream or by the queue's next try, finds the episode its first
// delivery opened (store.OpenEpisode, episodes_open_thread), so it opens no second one and
// delivery opened (store.Episodes.Open, episodes_open_thread), so it opens no second one and
// writes no second card. An episode or a card that fails costs the card, not the answer: it
// is logged and the message is answered all the same.
func (s *Server) chatEpisode(ctx context.Context, origin hookOrigin, event messageEvent, answering session.Spec) {
Expand Down
2 changes: 1 addition & 1 deletion acceleration/internal/api/chatinbound.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ func (s *Server) answerChatInboundForPeer(w http.ResponseWriter, r *http.Request
}

// answerOnce settles a queued delivery's row as its answer starts, so a try of it after that, on
// this router or another, answers nothing (store.StartChatInboundAnswer). answer is false when
// this router or another, answers nothing (store.ChatInbounds.StartAnswer). answer is false when
// the message is not to be answered now, and settled then says whether that holds: its answer
// already started, or the row could not be written and a later try may. A hook is never tried
// again, so it settles nothing. A router that stops mid-answer leaves the message answered at
Expand Down
2 changes: 1 addition & 1 deletion acceleration/internal/api/configs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2179,7 +2179,7 @@ func (s *ConfigsSuite) TestNessyBesideSeveralOutboundToolsNamesThemAll() {

// TestNessyBesideAConnectorWithOneOutboundSourceAmongSeveralIsRefused: a connector sends data
// out if any of its sources may, not only the first. Manifest.Validate accepts several sources
// and CreateConnectorDefinition takes any manifest, so a custom connector can put a source that
// and store.ConnectorDefinitions.Revise takes any manifest, so a custom connector can put a source that
// says outbound: false before one that does not.
func (s *ConfigsSuite) TestNessyBesideAConnectorWithOneOutboundSourceAmongSeveralIsRefused() {
s.useInternalApp()
Expand Down
5 changes: 2 additions & 3 deletions acceleration/internal/api/connection_proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -406,9 +406,8 @@ func waitSeconds(wait time.Duration) string {
}

// auditProxyCall records one direct call the connection's client sent (T44): the provider's
// status, nil when no answer came, the time to its answer and the host it reached
// (20261007170000_connector_invocations_and_audit.sql). The call happened whatever the row
// does, so a row that cannot be written is logged.
// status, nil when no answer came, the time to its answer and the host it reached. The call
// happened whatever the row does, so a row that cannot be written is logged.
func (s *Server) auditProxyCall(ctx context.Context, connection store.ConnectorConnection, host string, status *int, latency int64) {
ctx, cancel := detachedWrite(ctx)
defer cancel()
Expand Down
2 changes: 1 addition & 1 deletion acceleration/internal/api/connection_proxy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1029,7 +1029,7 @@ func (s *ConnectionProxySuite) connectedInAnotherApp(id string) (*testClient, st
}

// awayFromAMinuteBoundary waits out a minute that ends in under five seconds, so the calls a
// test counts next fall in one of the cap's windows (core.Limiter.Take).
// test counts next fall in one of the cap's windows (core.Limiter.Admit).
func awayFromAMinuteBoundary() {
if left := time.Until(time.Now().Truncate(time.Minute).Add(time.Minute)); left < 5*time.Second {
time.Sleep(left)
Expand Down
Loading
Loading