AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 59

    Observability for Full-Stack and LLM Applications

    The tutor container from Cloud Deployment, Serverless and Managed Runtime Choices stayed warm, and Priya's lesson page still loaded.

    Course progress0%
    Focus
    16 guided sections
    Practice signal
    Concept-first lesson
    Career prep
    Foundation builder

    AI-Powered Full Stack Development · Lesson 59 · Production AI Products, Capstones and Career Readiness

    Lesson Overview

    The tutor container from Cloud Deployment, Serverless and Managed Runtime Choices stayed warm, and Priya's lesson page still loaded. The explanation did not. On-call searched the log for the request and found one line that contained the question text, priya@northwind.example, and MODEL_API_KEY=TEST_ONLY_MODEL_TOKEN. A second line, tagged organizationId=northwind, included lrn_contoso because a retrieved chunk id had been copied into the log payload with its source tenant still attached. Cold starts, truncated streams, token counts, and the eval worker's cursor were not in any of those lines. The runtime placement was real. The signals that lesson promised Module 6 were not.

    Observability here is three records of the same click, each with a job. A trace is the path of one request across the player, the API, Postgres, and the model call, joined by a trace id. A metric is a number you can aggregate: token counts, time to first token, cold starts, truncations, completed worker cases. A log is one redacted JSON line for that span, so a human can read the path without opening a prompt store. None of the three is a transcript. RAG Evaluation and Observability already kept questions out of retrieval traces. Secrets, Privacy, Data Retention and Compliance Basics already defined redactForTrace. This lesson applies both rules to the full stack that lesson 58 deployed: CDN, serverless progress route, tutor container, eval worker, and the model call.

    Northwind and Contoso stay fenced. A span records organizationId so an authorized Northwind operator can find Northwind's slow tutor. The same span is rejected when its attributes contain a marker that belongs to another tenant. Metric labels stay low-cardinality: route, profile, status. Tenant id, learner id, and question text are not series names.

    Planning assumptions:

    • The lab exports nothing. emitSpan and emitMetric return values a test can assert. A later collector maps them to OpenTelemetry. Vendor dashboards change. The allowlists do not.
    • W3C traceparent is accepted when the player sends one. The API mints a trace id when it does not. The browser's idempotency key is a different field. Cost dedupe in the next lesson uses that key. Traces use the trace id.
    • Allowed LLM attributes are profile id, prompt version, token counts, time to first token, and a status code. Question text, messages, completions, emails, and secrets are forbidden keys.
    • Fixture marker TEST_ONLY_MODEL_TOKEN and the prefix tlp_live_ must not survive into a span. An assignment such as MODEL_API_KEY=... is redacted inside an error string. A bare token is a hard reject.
    • Illustrative alert thresholds in this lesson are lab numbers, not a contractual SLO. Confirm them against traffic before you page a human.
    • No provider key, no account id, and no learner mailbox appear in source. The email in the tests exists so redaction can remove it.

    Learning Objectives

    By the end of this lesson you will be able to:

    1. Separate a trace, a metric, and a log, and name which question each one answers for the tutor path.
    2. Carry one trace id from the HTTP span through the Postgres span and the model span.
    3. Mint a trace id at the API when the player does not send traceparent, and keep that id distinct from the idempotency key.
    4. Record an LLM span with profile, prompt version, token counts, time to first token, and status.
    5. Reject prompt text, completions, emails-as-keys, authorization headers, and cookies before a span is stored.
    6. Redact an email or a KEY= assignment that leaked into an error string, and reject a bare fixture token.
    7. Reject a Northwind span that contains a Contoso learner marker.
    8. Emit token, latency, cold-start, truncation, and worker-cursor metrics with only route, profile, and status labels.
    9. Refuse a metric label that names a tenant, a learner, or a question.
    10. Render one JSON log line from the safe span so the log and the trace cannot drift.
    11. Sample successful progress reads and keep every model span and every error.
    12. Write an alert rule for truncated tutor streams and for production cold starts without paging on preview scale-to-zero.
    13. Point a support query at organizationId on the span, with the same tenant fence as the database.
    14. Hand the next lesson token counts and time-to-first-token that a ledger can sum, without handing it the prompt.

    Prerequisites

    Detailed Core Concepts

    Three records, three questions

    A single unstructured line tried to be a transcript, a bill, and a stack trace. It failed at all three, and it stored data the product is not allowed to keep in an operational system.

    RecordQuestion it answersExample for Priya's clickMust not contain
    TraceWhere did the time go on this request?http.server 40 ms, db.query 12 ms, llm.chat 2.4 sPrompt, completion, email, key
    MetricHow often, how slow, how expensive, across requests?tutor.ttft_ms, tutor.tokens, tutor.stream_truncatedTenant id, learner id, question
    LogWhat did the safe span say, in one line a human can grep by trace id?JSON of the LLM spanA second copy of the raw body

    The trace explains one Northwind timeout. The metric tells you whether timeouts are one learner or two percent of tutor traffic. The log is how on-call reads the trace when the trace UI is down. If the log is built by concatenating the request body, you have a fourth system with worse rules. logLine prints the span you already accepted.

    What an LLM span is allowed to remember

    A model call is a span named llm.chat, parented to http.server, with the same traceId and the same organizationId. The attributes that earn their place are the ones a later lesson can aggregate without re-identifying a person:

    • profile is your id (draft-small, draft-standard, draft-long), not a vendor secret and not a model name pasted from a console.
    • promptVersion is the template id, such as tutor-answer-v3.
    • inputTokens and outputTokens are counts.
    • ttftMs is the time until the first token was available to flush. When the handler buffers the whole completion, this number equals total time, which is the bug the next lesson will refuse.
    • status is ok, timeout, or unavailable.
    • questionChars is a length. The question itself stays in the product database under the retention clock, for a person who is allowed to read that row.

    OpenTelemetry is the export shape you will grow into: a trace, a span, attributes, and metrics. When you add a collector, map inputTokens to gen_ai.usage.input_tokens and profile to gen_ai.request.model. Leave content-capture features off. A semantic convention that allows prompt text is not a requirement to send prompt text. This lab's attribute names stay stable even if the export names move.

    Redaction is the second gate, not the design

    Build the attribute bag from known fields. Then run two checks. Forbidden keys (prompt, question, completion, messages, email, authorization, cookie, body, and key aliases) fail the emit. The call site is wrong, and dropping the key silently would hide that. An error string may contain an email or a MODEL_API_KEY= assignment because exception text is not a designed field. That string is redacted. If TEST_ONLY_MODEL_TOKEN or tlp_live_ still remains after redaction, the emit fails. Redaction is not permission to log the raw line first.

    Lesson 52 classified unknown fields as personal. The tracer agrees: a key that is not on the allowlist for llm.chat is rejected. Progress spans may carry queryName and rowCount. They may not carry the SQL text, because a literal in the SQL is how an email re-enters the log.

    Tenant id belongs on the span, not on the metric

    organizationId is how you authorize a trace query. Northwind's on-call role can read spans where organizationId is northwind. The trace store applies the same predicate as Postgres. A copied chunk that still says lrn_contoso fails emitSpan when the context's foreign-marker list includes that id. The list is supplied by the tenant fence. The tracer does not hard-code customer names. The test passes lrn_contoso for a Northwind session so the rule is visible.

    Metrics are different. A label creates a time series. Learner id and question hash explode the series count and turn the metrics system into a second transcript store. Tenant id on a metric also builds a dashboard that mixes tenants the moment someone removes a filter. Per-tenant spend is a ledger row in the next lesson, written under the organization's allowance. It is not a Prometheus label.

    Sampling, retention, and the worker

    Successful progress reads are numerous and cheap. Keep a sample. Model spans are the cost and the latency. Keep all of them. Errors and truncations are the incident. Keep all of them. A sampler that keeps one percent of everything will drop the truncated stream you deployed the container to avoid.

    Retention follows the privacy policy because the span was built to contain operational data only. Seven days is the lab clock for traces and logs. Metrics stay as rollups. If a redaction bug lands an email in a span, the span is personal data and the purge job from lesson 52 applies. Do not lengthen retention "in case we need the prompt later." The prompt was never supposed to be there.

    The eval worker emits worker.batch with runId, nextCaseIndex, and spentUnits, and a metric worker.cases_completed. It does not emit case text. A cursor that does not advance is the kill from lesson 58, visible without reading a provider bill.

    Alerts that match the runtime

    Preview scale-to-zero produces cold starts on purpose. Production tutor cold starts mean minInstances was copied from preview. Page on production only. Truncation rate pages when the sample count is high enough that one learner cannot wake the rota. Token totals are a review metric for the next lesson, not a page, until a spend cap is actually crossed.

    Architecture and Request Flow

    flowchart TB
      subgraph edge [Edge]
        Browser[Browser session]
      end
    
      subgraph api [Tutor container]
        HTTP[http.server span]
        DB[db.query span]
        LLM[llm.chat span]
        Gate[emitSpan and emitMetric]
      end
    
      subgraph out [Operational store]
        Traces[(Traces by organizationId)]
        Metrics[Metrics: route profile status]
        Logs[Redacted JSON logs]
      end
    
      Browser -->|traceparent or none| HTTP
      HTTP --> DB
      HTTP --> LLM
      DB --> Gate
      LLM --> Gate
      Gate --> Traces
      Gate --> Metrics
      Gate --> Logs
    text
    Priya clicks Explain on the primary-key lesson
    -> player sends the session and, when it has one, traceparent
    -> API mints a trace id if traceparent is absent
    -> http.server span opens with organizationId northwind
    -> db.query child: queryName progress_by_lesson, rowCount
    -> llm.chat child: profile, promptVersion, tokens, ttftMs, status
    -> emitSpan rejects forbidden keys and foreign markers
    -> emitMetric writes tokens, ttft, truncation, cold start
    -> logLine prints the safe LLM span only
    Contoso's click is a different trace id and organizationId contoso
    -> a Northwind query cannot read it
    Eval worker
    -> worker.batch span with runId and nextCaseIndex
    -> metric worker.cases_completed

    Trust boundary: the browser never receives the provider key and never uploads a span that the API stores as-is. Client timing hints may arrive as numbers. Client-supplied attribute maps are ignored. The server builds the bag.

    Failure point to name in review: a trace backend without organizationId in the query predicate is a cross-tenant store, even when every application query is fenced.

    Step-by-step Implementation

    Package: packages/observe/. Pure functions. No collector SDK. Tests call the same functions the tutor path will call.

    Step 1: Span and metric types

    packages/observe/src/types.ts

    typescript
    export type SpanName = "http.server" | "db.query" | "llm.chat" | "worker.batch";
    export type TutorStatus = "ok" | "timeout" | "unavailable";
    /** Attributes are numbers, flags, and short codes. Free text is limited to error. */
    export type AttributeValue = string | number | boolean;
    export interface SpanDraft {
    traceId: string;
    spanId: string;
    parentSpanId: string | null;
    name: SpanName;
    organizationId: string;
    durationMs: number;
    attributes: Readonly<Record<string, AttributeValue>>;
    }
    export interface SafeSpan {
    traceId: string;
    spanId: string;
    parentSpanId: string | null;
    name: SpanName;
    organizationId: string;
    durationMs: number;
    attributes: Record<string, AttributeValue>;
    }
    export type MetricName =
    | "runtime.cold_start"
    | "tutor.stream_truncated"
    | "tutor.tokens"
    | "tutor.ttft_ms"
    | "worker.cases_completed";
    export interface MetricPoint {
    name: MetricName;
    value: number;
    labels: { route: string; profile: string; status: string };
    }
    export interface EmitContext {
    sessionOrganizationId: string;
    /** Ids that belong to other tenants. The span may not contain them. */
    foreignMarkers: readonly string[];
    }

    organizationId is a field, not an attribute, so the fence is structural. Labels on MetricPoint have exactly three keys. A wider bag is rejected in emitMetric before a point exists.

    Step 2: Redact, fence, and emit

    packages/observe/src/emit.ts

    typescript
    import type { AttributeValue, EmitContext, MetricPoint, SafeSpan, SpanDraft } from "./types.js";
    const FORBIDDEN_KEYS = new Set([
    "prompt",
    "question",
    "completion",
    "messages",
    "transcript",
    "email",
    "displayname",
    "authorization",
    "cookie",
    "body",
    "apikey",
    "api_key",
    "sql",
    ]);
    export type EmitFailure = "forbidden_attribute" | "tenant_mismatch" | "secret_in_value" | "bad_label";
    /** Fresh regexes on each call. A shared /g pattern keeps lastIndex and can skip the next span. */
    export function redactFreeText(text: string): string {
    return text
    .replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, "[redacted-email]")
    .replace(/(?:api[_-]?key|token|secret|authorization)\s*[:=]\s*\S+/gi, "[redacted-secret]");
    }
    function containsEmail(text: string): boolean {
    return /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/.test(text);
    }
    function containsRawSecret(text: string): boolean {
    return text.includes("TEST_ONLY_MODEL_TOKEN") || text.includes("tlp_live_");
    }
    export function emitSpan(
    draft: SpanDraft,
    ctx: EmitContext,
    ): { ok: true; span: SafeSpan } | { ok: false; code: EmitFailure } {
    if (draft.organizationId !== ctx.sessionOrganizationId) {
    return { ok: false, code: "tenant_mismatch" };
    }
    const attributes: Record<string, AttributeValue> = {};
    for (const [key, value] of Object.entries(draft.attributes)) {
    if (FORBIDDEN_KEYS.has(key.toLowerCase())) {
    return { ok: false, code: "forbidden_attribute" };
    }
    if (typeof value === "string") {
    const cleaned = key === "error" ? redactFreeText(value) : value;
    if (containsRawSecret(cleaned) || containsEmail(cleaned)) {
    return { ok: false, code: "secret_in_value" };
    }
    for (const marker of ctx.foreignMarkers) {
    if (cleaned.includes(marker)) return { ok: false, code: "tenant_mismatch" };
    }
    attributes[key] = cleaned;
    } else {
    attributes[key] = value;
    }
    }
    return {
    ok: true,
    span: {
    traceId: draft.traceId,
    spanId: draft.spanId,
    parentSpanId: draft.parentSpanId,
    name: draft.name,
    organizationId: draft.organizationId,
    durationMs: draft.durationMs,
    attributes,
    },
    };
    }
    const LABEL_KEYS = ["route", "profile", "status"] as const;
    export function emitMetric(
    name: MetricPoint["name"],
    value: number,
    labels: Record<string, string>,
    ): { ok: true; point: MetricPoint } | { ok: false; code: "bad_label" } {
    const keys = Object.keys(labels);
    if (keys.length !== LABEL_KEYS.length) return { ok: false, code: "bad_label" };
    for (const key of LABEL_KEYS) {
    if (typeof labels[key] !== "string" || labels[key].length === 0) {
    return { ok: false, code: "bad_label" };
    }
    }
    return {
    ok: true,
    point: {
    name,
    value,
    labels: { route: labels.route, profile: labels.profile, status: labels.status },
    },
    };
    }
    /** The log is the span. It is not a second channel with its own fields. */
    export function logLine(span: SafeSpan): string {
    return JSON.stringify({
    traceId: span.traceId,
    spanId: span.spanId,
    parentSpanId: span.parentSpanId,
    name: span.name,
    organizationId: span.organizationId,
    durationMs: span.durationMs,
    attributes: span.attributes,
    });
    }

    Each call builds its own regex. A module-level /g pattern remembers lastIndex, so a second span in the same process can skip an email the first replace already consumed. The tests redact one error string. The assignment adds a second string in the same process so that hazard cannot return.

    Step 3: One tutor click becomes spans and metrics

    packages/observe/src/tutor.ts

    typescript
    import { emitMetric, emitSpan, logLine } from "./emit.js";
    import type { EmitContext, MetricPoint, SafeSpan, TutorStatus } from "./types.js";
    export interface TutorObservation {
    traceId: string;
    httpSpanId: string;
    llmSpanId: string;
    organizationId: string;
    profile: string;
    promptVersion: string;
    questionChars: number;
    inputTokens: number;
    outputTokens: number;
    ttftMs: number;
    totalMs: number;
    status: TutorStatus;
    coldStart: boolean;
    }
    export function observeTutor(
    input: TutorObservation,
    ctx: EmitContext,
    ): { ok: true; spans: SafeSpan[]; metrics: MetricPoint[]; log: string } | { ok: false; code: string } {
    const http = emitSpan(
    {
    traceId: input.traceId,
    spanId: input.httpSpanId,
    parentSpanId: null,
    name: "http.server",
    organizationId: input.organizationId,
    durationMs: input.totalMs,
    attributes: { route: "tutor_stream", status: input.status },
    },
    ctx,
    );
    if (!http.ok) return http;
    const llm = emitSpan(
    {
    traceId: input.traceId,
    spanId: input.llmSpanId,
    parentSpanId: input.httpSpanId,
    name: "llm.chat",
    organizationId: input.organizationId,
    durationMs: input.totalMs,
    attributes: {
    profile: input.profile,
    promptVersion: input.promptVersion,
    questionChars: input.questionChars,
    inputTokens: input.inputTokens,
    outputTokens: input.outputTokens,
    ttftMs: input.ttftMs,
    status: input.status,
    },
    },
    ctx,
    );
    if (!llm.ok) return llm;
    const metrics: MetricPoint[] = [];
    const tokenPoint = emitMetric("tutor.tokens", input.inputTokens + input.outputTokens, {
    route: "tutor_stream",
    profile: input.profile,
    status: input.status,
    });
    const ttftPoint = emitMetric("tutor.ttft_ms", input.ttftMs, {
    route: "tutor_stream",
    profile: input.profile,
    status: input.status,
    });
    if (!tokenPoint.ok || !ttftPoint.ok) return { ok: false, code: "bad_label" };
    metrics.push(tokenPoint.point, ttftPoint.point);
    if (input.status === "timeout") {
    const truncated = emitMetric("tutor.stream_truncated", 1, {
    route: "tutor_stream",
    profile: input.profile,
    status: "timeout",
    });
    if (!truncated.ok) return truncated;
    metrics.push(truncated.point);
    }
    if (input.coldStart) {
    const cold = emitMetric("runtime.cold_start", 1, {
    route: "tutor_stream",
    profile: input.profile,
    status: input.status,
    });
    if (!cold.ok) return cold;
    metrics.push(cold.point);
    }
    return { ok: true, spans: [http.span, llm.span], metrics, log: logLine(llm.span) };
    }

    observeTutor prints with logLine from emit.ts. A second printer that stringifies the raw observation would put the question back into the log. One function keeps the log and the span on the same allowlist.

    The HTTP span and the LLM span share traceId and organizationId. parentSpanId on the model span is the HTTP span id. A database span is the same shape with name: "db.query" and attributes queryName and rowCount. Add it beside the model span. Do not put the SQL string in.

    Step 4: Alert sketch

    deploy/observe/alerts.yaml

    yaml
    # Lab thresholds. They are not an SLO. Raise minSamples with real traffic.
    alerts:
    - name: tutor_stream_truncated
    metric: tutor.stream_truncated
    window: 5m
    minSamples: 20
    condition: "rate > 0.02"
    environments: [production, preview]
    - name: prod_tutor_cold_start
    metric: runtime.cold_start
    labels:
    route: tutor_stream
    condition: "count > 0"
    environments: [production]
    - name: worker_cursor_stalled
    metric: worker.cases_completed
    window: 15m
    condition: "increase == 0 while a run is leased"
    environments: [production]

    Preview is absent from prod_tutor_cold_start because lesson 58 scales that environment to zero. Truncation still matters in preview: a fixture timeout is a product bug, a cold start is a policy.

    Step 5: Run

    bash
    node --test packages/observe/src/emit.test.ts packages/observe/src/tutor.test.ts

    Nothing is exported to a vendor. Cleanup is deleting the test process. If you later attach a collector, the cleanup is that collector's dev project, the same day, and the attribute allowlist stays in this package where CI can see it.

    Security

    • Authentication. Spans are written by the API process, not by the browser. A learner cannot post an attribute bag.
    • Authorization. Trace queries filter on organizationId from the operator's session. A Northwind role that can pass organizationId=contoso is the export bug from earlier lessons, moved into the trace store.
    • Least privilege. The tutor task role can write spans for its own organization. It cannot read Contoso spans. The worker role writes worker.batch and cannot attach learner emails. Dashboard editors are not database superusers.
    • Input validation. Forbidden keys fail closed. Foreign markers fail closed. Metric labels are an allowlist of three.
    • Secrets. The provider key stays in the secret store from lesson 58. It is not a span attribute. Error strings pass through redactFreeText. A bare TEST_ONLY_MODEL_TOKEN or tlp_live_ fails the emit.
    • Tenant isolation. lrn_contoso on a Northwind span is tenant_mismatch. Chunk metadata is filtered before it becomes an attribute. The fence is the caller's marker list, sourced from the tenant boundary, not from the model.
    • Privacy. Question text is not operational data. Support reads it from the product row under privacy-retention-v1, or not at all. Traces are not a way around that clock.
    • Injection. Attribute values are data. They are not interpolated into a query string in the trace UI. A status code is a closed set.

    Prompt injection still belongs to the application guard from the security module. A span that records status=ok does not mean the answer was true. Do not alert on model-authored text. Alert on status codes you assigned.

    Error Handling

    EventOperator or learner seesSystem does
    Forbidden attribute such as promptRequest still returns the tutor fallback the product already definedEmit fails. The span is not stored. A test fails if the route still calls emit with that key
    Email inside errorLog shows [redacted-email]redactFreeText runs before storage
    Bare fixture tokenEmit fails with secret_in_valueNo span. Rotate anything that was a real key. The fixture token was never real
    Foreign marker on the spanEmit fails with tenant_mismatchNo span. Fix the attribute source. Do not strip the marker and continue
    Missing traceparentLearner sees no changeAPI mints a trace id and puts it on the response header for support
    Collector downLearner path stays upDrop or buffer operational spans. Do not block the tutor on the trace export
    Timeout statusLearner sees the typed timeout from lesson 58tutor.stream_truncated increments. The lesson page stays
    Preview cold startA slower first requestMetric may increment. The production alert does not include preview

    If emit fails, the user response is unchanged. Observability must not take down Explain. The failure is logged as a counter observe.rejected with a code label from the closed set, not with the rejected value.

    Testing

    packages/observe/src/emit.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { emitMetric, emitSpan, logLine } from "./emit.js";
    import type { SpanDraft } from "./types.js";
    const ctx = { sessionOrganizationId: "northwind", foreignMarkers: ["lrn_contoso"] };
    function draft(attributes: SpanDraft["attributes"]): SpanDraft {
    return {
    traceId: "trace_n_1",
    spanId: "span_llm_1",
    parentSpanId: "span_http_1",
    name: "llm.chat",
    organizationId: "northwind",
    durationMs: 2400,
    attributes,
    };
    }
    test("rejects a prompt attribute", () => {
    const result = emitSpan(draft({ prompt: "what is a primary key" }), ctx);
    assert.equal(result.ok, false);
    if (!result.ok) assert.equal(result.code, "forbidden_attribute");
    });
    test("redacts an email inside an error string", () => {
    const result = emitSpan(draft({ error: "failed for priya@northwind.example" }), ctx);
    assert.equal(result.ok, true);
    if (result.ok) {
    assert.equal(result.span.attributes.error, "failed for [redacted-email]");
    assert.equal(logLine(result.span).includes("priya@"), false);
    }
    });
    test("rejects a bare fixture token", () => {
    const result = emitSpan(draft({ error: "saw TEST_ONLY_MODEL_TOKEN in config" }), ctx);
    assert.equal(result.ok, false);
    if (!result.ok) assert.equal(result.code, "secret_in_value");
    });
    test("rejects a Contoso learner marker on a Northwind span", () => {
    const result = emitSpan(draft({ learnerId: "lrn_contoso" }), ctx);
    assert.equal(result.ok, false);
    if (!result.ok) assert.equal(result.code, "tenant_mismatch");
    });
    test("rejects a metric that tries to label a tenant", () => {
    const result = emitMetric("tutor.tokens", 120, {
    route: "tutor_stream",
    profile: "draft-small",
    status: "ok",
    organizationId: "northwind",
    });
    assert.equal(result.ok, false);
    if (!result.ok) assert.equal(result.code, "bad_label");
    });

    packages/observe/src/tutor.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { observeTutor } from "./tutor.js";
    const ctx = { sessionOrganizationId: "northwind", foreignMarkers: ["lrn_contoso"] };
    test("links the model span to the http span and counts a truncation", () => {
    const result = observeTutor(
    {
    traceId: "trace_n_1",
    httpSpanId: "span_http_1",
    llmSpanId: "span_llm_1",
    organizationId: "northwind",
    profile: "draft-small",
    promptVersion: "tutor-answer-v3",
    questionChars: 22,
    inputTokens: 400,
    outputTokens: 80,
    ttftMs: 500,
    totalMs: 2400,
    status: "timeout",
    coldStart: false,
    },
    ctx,
    );
    assert.equal(result.ok, true);
    if (!result.ok) return;
    const llm = result.spans.find((span) => span.name === "llm.chat");
    assert.ok(llm);
    assert.equal(llm?.parentSpanId, "span_http_1");
    assert.equal(llm?.traceId, "trace_n_1");
    assert.equal(result.metrics.some((point) => point.name === "tutor.stream_truncated"), true);
    assert.equal(result.log.includes("what is a primary key"), false);
    });

    Add a test that a Contoso session (sessionOrganizationId: "contoso") cannot emit a span whose organizationId is northwind, and a test that status: "ok" does not emit tutor.stream_truncated. Add a test that a redacted MODEL_API_KEY=TEST_ONLY_MODEL_TOKEN assignment becomes [redacted-secret] and that the fixture marker is absent from logLine.

    Performance and Cost

    Observability has its own bill. A span per progress read, stored with a question body, costs more than the progress query and recreates the privacy incident. The design keeps model spans, samples successful progress spans, and stores counts rather than text.

    • Cardinality is the metric cost. Three labels with closed values stay cheap. A question hash label is a new series per click and will dominate the bill.
    • Export on the request path adds latency. emitSpan is in-process and cheap. A synchronous vendor HTTP call inside the tutor deadline is not. Buffer and flush off the learner path. The flush uses the worker pattern when the buffer is large. It never holds the stream open.
    • Sampling saves storage on progress reads. It is not applied to llm.chat, timeouts, or secret_in_value rejects. Those are the events you bought the system to see.
    • Token metrics are counts, not a price. The next lesson converts counts into relative units per organization. Do not put a currency calculation in the tracer. Prices move. The count does not.
    • Log volume follows span volume if logLine is one line per span. That is acceptable. A debug flag that prints the provider payload is not, and it will dominate both cost and risk.
    • Trace ids are 16 bytes of hex in W3C form, or a short lab id such as trace_n_1 in tests. Do not use the question text as an id in order to "make grep easier."

    Illustrative ratio, not a quote: one JSON line of attribute codes is kilobytes smaller than a prompt plus a completion. Multiply by tutor opens before you enable content capture because a vendor toggle made it convenient.

    Knowledge Check

    1. What problem does observability solve for this product?

    It makes the lesson 58 runtime visible. A Northwind tutor timeout can be traced across HTTP, Postgres, and the model call. Token counts, time to first token, truncations, cold starts, and worker cursors become metrics. The log is a redacted copy of the span. The prompt, the email, the provider key, and Contoso's learner id stay out of that system.

    2. What alternatives exist, and when would you choose each?

    Application logs alone fit a single process while you are still on one container and the volume is tiny. They stop fitting when the model call, the database, and the worker must be joined, or when the log becomes a transcript. A full trace vendor fits once the attribute allowlist is enforced in your process. Tracing only the model and not the database hides a slow query that looked like a slow completion. Metrics without traces tell you the rate and not the request. Keep all three, with traces sampled only for successful short reads.

    3. Which data, identity, and trust boundaries matter?

    The browser sends a session and optionally traceparent. It does not send the attribute bag you store. organizationId comes from the session. Foreign markers are rejected. The provider key is not an attribute. Trace queries use the operator's tenant. Metric labels are route, profile, and status. Support reads question text from the product store under the retention policy, not from the trace.

    4. What can fail, and how should the system respond?

    A forbidden key or a foreign marker fails the emit and leaves the learner response on its existing fallback path. An email in an error string is redacted. A bare fixture token fails the emit. A down collector does not block Explain. A timeout increments tutor.stream_truncated. A production cold start pages. A preview cold start does not. A stalled worker cursor pages when a run is leased and the completed-case metric does not move.

    5. How would you test quality, security, performance, and cost?

    Unit tests cover forbidden keys, email redaction, the bare fixture token, the Contoso marker on a Northwind span, rejected tenant metric labels, parent span linkage, and truncation metrics. Security review checks that logLine is the only logger on this path and that trace queries require organizationId. Performance review checks that export is off the request thread and that successful progress spans are sampled. Cost review checks cardinality and confirms content capture is off.

    Hands-on Assignment

    Lab note. Do not create a tracing vendor account. Do not put a provider key or a real email in the package. priya@northwind.example and TEST_ONLY_MODEL_TOKEN exist only inside tests.

    Problem. Record Priya's tutor click as a Northwind trace, a token metric, and one redacted log line. Show that the same functions refuse the prompt and refuse lrn_contoso.

    Tasks.

    1. Draw the path from the browser through http.server, db.query, and llm.chat into traces, metrics, and logs.
    2. Implement emitSpan, emitMetric, logLine, and observeTutor with the tests in this lesson, plus the three extra tests named above.
    3. Add a test that redacts two different error emails in one process, so a shared /g regex cannot skip the second span.
    4. Add a db.query child span whose attributes are queryName and rowCount.
    5. Add deploy/observe/alerts.yaml with truncation, production cold start, and stalled worker cursor.
    6. State what a Northwind operator can query, and what a metric dashboard is allowed to group by.
    7. List the fields the next lesson's cost ledger may read from the LLM span.

    Deliverable. Diagram, source with no secrets, test output, the alert file, and a short note on sampling versus keeping every model span.

    Challenge. Contoso and Northwind share one collector. A support tool lets an operator pass any organizationId. Explain the query predicate, the role that may read spans, and the test that fails when a Northwind session reads a Contoso trace id. The collector outage must not change the tutor HTTP status. A second constraint: legal asks to retain prompts in the trace for 90 days. Refuse, and point at the product retention clock instead.

    Rubric. Conceptual accuracy and architecture 20%. Working implementation and code quality 25%. Security, privacy, and responsible AI 20%. Testing, reliability, and observability 20%. Documentation and decision rationale 15%.

    Common Mistakes

    1. Logging the question and the completion. Symptom: the log store is a transcript database, and a support login can read every learner. Cause: console.log(body) in the catch path. Fix: forbidden keys, and logLine of the safe span only.
    2. Logging the provider key while debugging a timeout. Symptom: TEST_ONLY_MODEL_TOKEN or a live prefix in a file. Cause: the error printer dumped the environment. Fix: secret_in_value, redaction of assignments, and a boot check that still rejects tlp_live_ in traces.
    3. Putting tenant id on every metric. Symptom: a shared dashboard and a series per customer. Cause: labels copied from the span. Fix: tenant on the span and in the ledger, never as a metric label.
    4. Copying retrieved chunk metadata into attributes. Symptom: lrn_contoso on a Northwind trace. Cause: the chunk object was spread into the span. Fix: copy queryName and counts. Run the foreign-marker check.
    5. Sampling at one percent across the board. Symptom: the truncation incident is invisible. Cause: one sampler for progress and tutor. Fix: keep all llm.chat spans and all errors.
    6. A new trace id on each child call. Symptom: the database time and the model time cannot be joined. Cause: each client minted its own id. Fix: one traceId on the draft, parentSpanId for the child.
    7. Using the idempotency key as the trace id. Symptom: a learner retry overwrites the first attempt's timing. Cause: one header was reused for two jobs. Fix: trace id joins the attempt's spans. The idempotency key dedupes money in the next lesson.
    8. Blocking Explain on the collector. Symptom: tutor latency tracks the trace vendor. Cause: a synchronous export inside the deadline. Fix: in-process emit, async flush, learner path stays up.
    9. Storing SQL text. Symptom: emails appear inside db.query. Cause: the statement was logged with literals. Fix: queryName and rowCount.
    10. Paging on preview cold starts. Symptom: the rota wakes every morning for a policy you chose. Cause: the production alert included preview. Fix: cold-start pages list production only. Truncation still pages in both.

    Summary

    Observability is how TechLearningPro sees the runtime lesson 58 placed. A tutor click becomes an http.server span, a db.query span, and an llm.chat span under one trace id, with token counts, time to first token, and a status. Metrics use route, profile, and status. Logs print the safe span. Prompts, emails, provider keys, and the other tenant's learner ids are refused or redacted before storage. Northwind can explain a slow Northwind request. Contoso's traces stay on Contoso's side of the fence. The numbers on the LLM span are the input to cost and latency, which is the next lesson.

    Next Lesson Preview

    LLM Cost, Latency and Performance Engineering reads the token counts and ttftMs you just made safe to store. You will turn them into a per-organization allowance, refuse a buffered stream that hides time to first token, and stop a glossary click from spending the long-profile budget. The trace stays redacted. The ledger adds money-shaped units without putting tenant id on a metric.

    Further Reading

    Ready to mark this lesson complete?Track your journey across the entire course.