Skip to content
5 changes: 3 additions & 2 deletions .claude/skills/go/logging.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@ Read before you log a value, or read one back out of a log.

## What to log

- The ids that find a line are `customer`, `session`, `call` and `turn`. A job's are `task` and `run`. The failure is `error`.
- The ids that find a line are `app_id`, `session`, `call` and `turn`. A job's are `task` and `run`. The failure is `error`.
- Some lines still use `customer_id`, `session_id`, `call_id` or `err`. Do not copy them.
- `customer` is the old name of `app_id`; ClickHouse reads it only from lines older routers wrote.
- An end user's id is `user`, a call participant's `participant` (`bound` for the one a speech-to-speech model hears); `user_id` is the old name. The customer picks it and it is often an email, or `phone:` and a number for a channel user. Under these names the logger masks everything before an email's `@`, and it masks a `phone:` number anywhere. A bare numeric id is kept: its shape cannot tell it from an opaque one. A route's `{user_id}` segment is logged as `{user_id}`. Find a user's lines by `session`, `call` or `request_id`.
- Do not repeat what the logger carries: `customer`, `session`, `call` on the agent's (`agent.New`); `provider`, `model` on a provider's; `app_id`, `api_key` on a line logged with a request's context.
- Do not repeat what the logger carries: `app_id`, `session`, `call` on the agent's (`agent.New`); `provider`, `model` on a provider's; `app_id`, `api_key` on a line logged with a request's context.
- Name any other field after what it holds (`connector`, not `id`) and keep its value short. There is no `component` field: the message names the thing.
- Never a request body, nor a header that can hold a secret. Never a whole map or struct, unless a tool reads it back (below).
- A connector logs the body of a provider's answer one way: `core.LoggedBody(exchange.ErrorBody())`, the cut, redacted start of an error body.
Expand Down
2 changes: 1 addition & 1 deletion .claude/skills/scheduled-tasks/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,5 +245,5 @@ it also finds the job queue's `Failed to forward scheduled tasks`, which is nois
| `could not read when a scheduled task last ran` | error | `scheduled_tasks.go:637` |
| `could not pause a deleted config's scheduled tasks` | error | `internal/api/configs.go:309` |

Each line carries `task`, `run` and `customer` where it has them; the `error` field holds the
Each line carries `task`, `run` and `app_id` where it has them; the `error` field holds the
whole story the run's code leaves out.
14 changes: 7 additions & 7 deletions acceleration/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2174,13 +2174,13 @@ Everything above is what a request *did*. That it arrived at all is a log line,
request served, at info:

```
level=INFO msg="served a request" method=POST path=/v1/agents/sessions status=201 duration=425ms customer=examples request_id=… bytes=877 app_id=examples api_key=noauth
level=INFO msg="served a request" method=GET path=/v1/agents/sessions/d84a…/events status=101 duration=94ms customer=examples request_id=… app_id=examples api_key=noauth
level=INFO msg="served a request" method=POST path=/v1/agents/sessions status=201 duration=425ms request_id=… bytes=877 app_id=examples api_key=noauth
level=INFO msg="served a request" method=GET path=/v1/agents/sessions/d84a…/events status=101 duration=94ms request_id=… app_id=examples api_key=noauth
```

An authenticated request's line, and any line logged with its context, names its app as `app_id`
and the public key it came with as `api_key`, as the Stream platform's logs do (`customer` is the
same app as `app_id`). A request nobody authenticated carries neither. A Stream hook (`PhoneHook`,
and the public key it came with as `api_key`, as the Stream platform's logs do. Every other router
line that names the app names it as `app_id` too, never twice. A request nobody authenticated carries neither. A Stream hook (`PhoneHook`,
`ChatHook`, `ReceiveChatDelivery`) names the app it was verified to come from as `app_id` once its
signature checked out, and no `api_key`, since no key made it; one that did not check out names no
app, whatever its path says. A hook verified before the deployment knows its own app (a
Expand Down Expand Up @@ -2335,10 +2335,10 @@ that comes back after 400 days without a request shows as new.
To see why an organization's requests are refused, list its refusals by code from the access
log. The router writes one `served a request` line per request, with `error_code` on every refused
request. That includes a call hook or a socket that is refused with status 200 or 101, so the query
keeps those lines too. The line names the app in `customer`, or in `app_id` when the request was
turned away before it was accepted (for example a caller refused for its user level). A request refused for its usage categories names no app, so this query does not list it.
keeps those lines too. The line names the app in `app_id`, including a request turned away before it
was accepted (for example a caller refused for its user level). A request refused for its usage categories names no app, so this query does not list it.
ClickHouse holds these lines in `logs.agent_access_logs`. It takes `app_id` from the line's
`app_id`, and from `customer` when that is missing. The status is `response`. It keeps 14 days.
`app_id`, and from `customer`, the key older routers named it under, when that is missing. The status is `response`. It keeps 14 days.
Each cluster has its own ClickHouse: staging is `us-east1-acceleration`, and prod has three clusters, so run the query on
each. Find the organization's apps in Postgres first
(`SELECT app_id FROM app_organizations WHERE organization_id = '<org>'`), then:
Expand Down
2 changes: 1 addition & 1 deletion acceleration/cmd/router/optouts.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func runNormalizeOptOuts(ctx context.Context, settings config.Config, logger *sl
done, err := pgStore.OptOuts.Normalize(ctx, batch, func(unread []store.OptOut) {
for _, optOut := range unread {
logger.Warn("an opt-out's recipient looks like a phone number but has no one valid reading, and was kept as it is",
"opt_out", optOut.ID, "customer", optOut.CustomerID, "channel", optOut.Channel)
"opt_out", optOut.ID, "app_id", optOut.CustomerID, "channel", optOut.Channel)
}
})
fmt.Fprintf(out, "%d opt-outs rewritten into E.164, %d revoked; %d name a handle, not a number, and were kept\n",
Expand Down
10 changes: 5 additions & 5 deletions acceleration/cmd/router/replicate.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ func copyEverything(ctx context.Context, source *deployment, pgStore *store.Stor
return "", 0, err
}
if saved != nil {
logger.Info("carrying on from the last run here", "customer", as, "cursor", *saved)
logger.Info("carrying on from the last run here", "app_id", as, "cursor", *saved)
return as, *saved, nil
}
}
Expand Down Expand Up @@ -232,7 +232,7 @@ func copyEverything(ctx context.Context, source *deployment, pgStore *store.Stor
return "", 0, err
}
if saved != nil {
logger.Info("carrying on from the last run here", "customer", customerID, "cursor", *saved)
logger.Info("carrying on from the last run here", "app_id", customerID, "cursor", *saved)
return customerID, *saved, nil
}
}
Expand Down Expand Up @@ -271,15 +271,15 @@ func copyEverything(ctx context.Context, source *deployment, pgStore *store.Stor
return "", 0, err
}
if saved != nil {
logger.Info("carrying on from the last run here", "customer", customerID, "cursor", *saved)
logger.Info("carrying on from the last run here", "app_id", customerID, "cursor", *saved)
return customerID, *saved, nil
}
}
if err := pgStore.MoveCursors.Upsert(ctx, &store.MoveCursor{CustomerID: customerID, Source: source.url, Cursor: cursor, ReadAt: asked}); err != nil {
return "", 0, err
}

logger.Info("copied a customer", "customer", customerID, "rows", rows, "cursor", *cursor)
logger.Info("copied a customer", "app_id", customerID, "rows", rows, "cursor", *cursor)
warnLeftOut(logger, customerID, leftOut)
return customerID, *cursor, nil
}
Expand Down Expand Up @@ -408,7 +408,7 @@ func warnLeftOut(logger *slog.Logger, customerID string, numbers int) {
return
}
logger.Warn("left out numbers on the app's own sip trunk that another app holds here: add them to a trunk "+
"(POST /v1/phone/trunks/{id}/numbers) once the move is over", "customer", customerID, "numbers", numbers)
"(POST /v1/phone/trunks/{id}/numbers) once the move is over", "app_id", customerID, "numbers", numbers)
}

// caughtUpMessage is what --once prints when it has caught up. It names --as for the next run:
Expand Down
2 changes: 1 addition & 1 deletion acceleration/internal/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -772,7 +772,7 @@ func New(options Options) (*Agent, error) {
}
}

logger := options.Logger.With("customer", options.CustomerID, "session", options.SessionID, "call", options.CallID)
logger := options.Logger.With("app_id", options.CustomerID, "session", options.SessionID, "call", options.CallID)
owner := routing.Owner{
CustomerID: options.CustomerID,
Attribution: options.Attribution,
Expand Down
7 changes: 4 additions & 3 deletions acceleration/internal/agent/approval_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,16 +62,16 @@ func (s *AgentSuite) TestAYesRunsTheCallOnceWithItsOwnID() {

// Keys of a line for a call that was answered with its question, as main logs them: the asked
// line has only approval added to them.
var askedLineKeys = []string{"agent_id", "app_id", "call", "customer", "duration_ms", "error_code", "level", "msg",
var askedLineKeys = []string{"agent_id", "app_id", "call", "duration_ms", "error_code", "level", "msg",
"outcome", "session", "success", "time", "tool", "tool_call", "turn"}

// confirmationLineKeys are the keys the confirmation's line has: the run it approved has its
// own line, with the connector and the error.
var confirmationLineKeys = []string{"agent_id", "app_id", "call", "customer", "duration_ms", "level", "msg",
var confirmationLineKeys = []string{"agent_id", "app_id", "call", "duration_ms", "level", "msg",
"outcome", "session", "success", "time", "tool", "tool_call", "turn"}

// connectorLineKeys are the keys main logs a connector's call with that asks nothing.
var connectorLineKeys = []string{"agent_id", "app_id", "call", "connector", "customer", "duration_ms", "error_code",
var connectorLineKeys = []string{"agent_id", "app_id", "call", "connector", "duration_ms", "error_code",
"level", "msg", "outcome", "session", "success", "time", "tool", "tool_call", "turn"}

// confirmedLines has the caller asked whether to book order 12 and answer with arguments, run
Expand Down Expand Up @@ -105,6 +105,7 @@ func (s *AgentSuite) TestAnApprovedCallIsLoggedUnderItsOwnName() {
})

s.Require().Len(lines, 3)
s.Equal([]int{1, 1, 1}, s.logs.keyCounts(toolBack, "app_id"), "the session logger's app is each line's only one")
asked, ran, confirmed := lines[0], lines[1], lines[2]
s.Equal("lookup_order", asked["tool"])
s.Equal("call-1", asked["tool_call"])
Expand Down
8 changes: 4 additions & 4 deletions acceleration/internal/agent/telephony.go
Original file line number Diff line number Diff line change
Expand Up @@ -838,16 +838,16 @@ func (a *Agent) executeTool(ctx context.Context, cancel context.CancelFunc, requ
})
}

// loggedTool is what "a tool call came back" says beside the agent logger's customer, session and
// call: whose agent it was, under the keys "model call timing" names them with, the connector
// loggedTool is what "a tool call came back" says beside the agent logger's app_id, session and
// call: whose agent it was, under the key "model call timing" names it with, the connector
// the tool belongs to, and whether it failed and how. A call fails when it returned err or
// its runner reported a failure (ToolReport); error_code is the runner's, else timeout or
// cancelled for a context that ended, else error. The error a connector call returned is
// never logged, only what its runner reported, redacted; nor is the one a caller's own tool
// failed with (ToolReport.Client). What a call was asked and answered is not logged: it is the
// caller's and its users'.
func (a *Agent) loggedTool(report ToolReport, err error) []any {
fields := []any{"app_id", a.options.CustomerID, "agent_id", a.options.AgentID}
fields := []any{"agent_id", a.options.AgentID}
if report.Connector != "" {
fields = append(fields, "connector", report.Connector)
}
Expand All @@ -874,7 +874,7 @@ func (a *Agent) loggedTool(report ToolReport, err error) []any {
// loggedAnswer is loggedTool for a confirmation: who, and whether the answer failed; no
// connector, error_code or error, which belong to the line of the run it approved.
func (a *Agent) loggedAnswer(err error) []any {
return []any{"app_id", a.options.CustomerID, "agent_id", a.options.AgentID, "success", err == nil}
return []any{"agent_id", a.options.AgentID, "success", err == nil}
}

// logToolBack writes "a tool call came back" for call, which ran in its TurnID for took and
Expand Down
3 changes: 2 additions & 1 deletion acceleration/internal/agent/turnlinks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,9 @@ func (s *AgentSuite) TestAToolCallIsLoggedWhenItComesBack() {
s.Contains(back, "duration_ms")
s.NotContains(back, "arguments", "what a caller's tool is given is theirs")
s.NotContains(back, "result", "what a caller's tool returns is theirs")
s.Equal("acme", back["customer"])
s.Equal("acme", back["app_id"], "the app is named as the model call line names it")
s.Equal([]int{1}, s.logs.keyCounts(toolBack, "app_id"), "the session logger's app is the line's only one")
s.NotContains(back, "customer")
s.Equal(s.agentID, back["agent_id"])
s.Equal(true, back["success"])
s.Equal("", back["error_code"])
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 @@ -403,7 +403,7 @@ func (s *Server) auditAs(ctx context.Context, customerID string, record auditRec
defer cancel()
if err := s.store.AuditEntries.Insert(ctx, &entry); err != nil {
s.logger.Error("could not record a configuration change",
"customer", customerID, "resource", record.ResourceType, "id", record.ResourceID,
"app_id", customerID, "resource", record.ResourceType, "id", record.ResourceID,
"error", err)
}
}
Expand Down
2 changes: 1 addition & 1 deletion acceleration/internal/api/callhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func (s *Server) answerCall(w http.ResponseWriter, r *http.Request, logger *slog

bridge, err := s.phone.InboundBridge(r.Context(), plans.vendor, to)
// InboundBridge notes the number's app once the number resolves, before it refuses one.
logger = logger.With("customer", activity.NotedCustomer(r.Context()))
logger = logger.With("app_id", activity.NotedCustomer(r.Context()))
if errors.Is(err, phone.ErrNoSealer) {
plans.hangUp(w, logger, "hung up a "+plans.vendor+" call: this router has no key to open trunk passwords: "+
"set ROUTER_DEV_KEK (local), or ROUTER_AUTH_KEK_V1_WRAPPED with ROUTER_AUTH_KMS_KEY (hosted), then attach the number again", "to", to)
Expand Down
20 changes: 10 additions & 10 deletions acceleration/internal/api/callhooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ func (s *Server) dispatchArrivingCall(w http.ResponseWriter, r *http.Request, or
if _, err := s.store.TelephonySuspensions.Get(r.Context(), number.CustomerID); !errors.Is(err, store.ErrNotSuspended) {
noteRefusal(w, codeTelephonySuspended)
s.refuseArrivingCall(r.Context(), number, callType, callID, event.SessionID, "refused an arriving call to a suspended app",
"call", event.CallCid, "customer", number.CustomerID, "error", err)
"call", event.CallCid, "app_id", number.CustomerID, "error", err)
return true
}
// The vendor bills the minutes of a call an agent answers, and the agent is billed work,
Expand All @@ -286,7 +286,7 @@ func (s *Server) dispatchArrivingCall(w http.ResponseWriter, r *http.Request, or
answer, _ := moneyError(err)
noteRefusal(w, answer.Code)
s.refuseArrivingCall(r.Context(), number, callType, callID, event.SessionID, "refused an arriving call to an organization that may not pay for it",
"call", event.CallCid, "customer", number.CustomerID, "code", answer.Code)
"call", event.CallCid, "app_id", number.CustomerID, "code", answer.Code)
return true
}
// Only a call that rings a number is worth recording as delivered: every video call in
Expand All @@ -300,7 +300,7 @@ func (s *Server) dispatchArrivingCall(w http.ResponseWriter, r *http.Request, or
if s.sessions == nil {
noteRefusal(w, errNoSessions.Code)
s.refuseArrivingCall(r.Context(), number, callType, callID, event.SessionID, "refused an arriving call to a number with an agent on a router that runs no sessions",
"call", event.CallCid, "customer", number.CustomerID, "number", number.E164, "config", number.ConfigID)
"call", event.CallCid, "app_id", number.CustomerID, "number", number.E164, "config", number.ConfigID)
return true
}
// The agent joins before it is answering, which can outlast Stream's wait for the
Expand Down Expand Up @@ -332,16 +332,16 @@ func (s *Server) dispatchArrivingCall(w http.ResponseWriter, r *http.Request, or
// Somebody is listening to a ringing phone that nothing is going to answer, which
// is the most useful error this service can report.
s.logger.Error("nobody could answer an arriving call",
"call", event.CallCid, "session_id", event.SessionID, "customer", number.CustomerID,
"call", event.CallCid, "session_id", event.SessionID, "app_id", number.CustomerID,
"number", number.E164, "error", err)
noteRefusal(w, unavailable("").Code)
s.refuseArrivingCall(r.Context(), number, callType, callID, event.SessionID, "refused an arriving call no worker could take",
"call", event.CallCid, "customer", number.CustomerID, "number", number.E164)
"call", event.CallCid, "app_id", number.CustomerID, "number", number.E164)
return true
}
s.pinHook(origin, number.CustomerID, event.CallCid)
s.logger.Info("handed an arriving call to a worker",
"call", event.CallCid, "session_id", event.SessionID, "customer", number.CustomerID,
"call", event.CallCid, "session_id", event.SessionID, "app_id", number.CustomerID,
"number", number.E164, "caller", call.CallerNumber, "worker", worker.ID)
arrived := []any{"worker", worker.ID, "stream_sip_host", phone.BridgeHost(number.BridgeURI)}
if call.SessionID != "" {
Expand All @@ -357,7 +357,7 @@ func (s *Server) answerWithAgent(ctx context.Context, sessions *session.Manager,
config, err := s.store.AgentConfigs.Get(ctx, number.CustomerID, number.ConfigID)
if err != nil {
s.refuseArrivingCall(ctx, number, callType, callID, event.SessionID, "refused an arriving call to a number whose agent is gone",
"call", event.CallCid, "customer", number.CustomerID, "number", number.E164,
"call", event.CallCid, "app_id", number.CustomerID, "number", number.E164,
"config", number.ConfigID, "error", err)
return
}
Expand Down Expand Up @@ -393,14 +393,14 @@ func (s *Server) answerWithAgent(ctx context.Context, sessions *session.Manager,
return
}
s.logger.Error("nobody could answer an arriving call",
"call", event.CallCid, "customer", number.CustomerID,
"call", event.CallCid, "app_id", number.CustomerID,
"number", number.E164, "config", number.ConfigID, "error", err)
s.refuseArrivingCall(ctx, number, callType, callID, event.SessionID, "refused an arriving call its agent could not answer",
"call", event.CallCid, "customer", number.CustomerID, "number", number.E164, "config", number.ConfigID)
"call", event.CallCid, "app_id", number.CustomerID, "number", number.E164, "config", number.ConfigID)
return
}
s.logger.Info("an agent answered an arriving call",
"call", event.CallCid, "customer", number.CustomerID,
"call", event.CallCid, "app_id", number.CustomerID,
"number", number.E164, "config", number.ConfigID, "session", created.ID())
}

Expand Down
4 changes: 2 additions & 2 deletions acceleration/internal/api/callhooks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,12 +207,12 @@ func (s *CallHooksSuite) TestTheAccessLineOfASignedCallNamesTheNumbersCustomer()
forged, _ := s.deliver(phone.CallHookPath, s.arriving("default:"+s.callID), sign(s.arriving("default:"+s.callID), "not the secret"))
s.Require().Equal(http.StatusUnauthorized, forged)
s.Require().Eventually(func() bool { return served(" status=401 ") }, settleFor, 10*time.Millisecond)
s.True(served(" status=401 ", ` customer="" `))
s.False(served(" status=401 ", "app_id="), "a call nobody signed names no app")

s.Require().Equal(http.StatusOK, s.arrive("default:"+s.callID))
s.Require().Eventually(func() bool { return served(" status=200 ") }, settleFor, 10*time.Millisecond)
// No worker takes it, so it is refused in a 200, with the code it is counted under.
s.True(served(" status=200 ", " customer="+s.customerID()+" ", " error_code=unavailable "))
s.True(served(" status=200 ", " app_id="+s.customerID()+" ", " error_code=unavailable "))
}

// thisTest is what the current test logged, so a line another test logged for a number
Expand Down
Loading
Loading