Session: Multi-turn format and generation methods

Updated at:

A session organizes the multi-turn trajectories of the same business conversation into ordered interactions and stores the complete snapshot of each turn. This topic provides two methods, scan SQL and application-side generation, which output the same main structure. This example uses the ingestion convention of "one trace per interaction turn" or "one log turn per interaction turn". If an actual turn spans multiple traces, you must first provide a business turn mapping. Do not directly treat the number of execution records as the number of user turns.

View the generated result first

In the order example, the first turn uses 110 tokens and the second turn uses 95 tokens, for a total of 205 tokens. The session spans 12,000 ms from start to end, and the total execution duration of the two turns is 4,000 ms. The former includes the wait time between turns, and the two values serve different purposes.

Only the session summary and turn summaries are expanded below.

{
  "sessionId": "session-demo-001",
  "startTimeMs": 1767225600000,
  "endTimeMs": 1767225612000,
  "durationMs": 12000,
  "turns": 2,
  "totalTokens": 205,
  "tokensComplete": true,
  "timeComplete": true,
  "input": "Query order 10001",
  "output": "It is expected to be delivered tomorrow.",
  "conversationTurns": [
    {"turn":1,"sourceKind":"otel_trace","trajectoryId":"11111111111111111111111111111111","traceId":"11111111111111111111111111111111","totalTokens":110,"input":"Query order 10001","output":"Order 10001 has been shipped."},
    {"turn":2,"sourceKind":"otel_trace","trajectoryId":"22222222222222222222222222222222","traceId":"22222222222222222222222222222222","totalTokens":95,"input":"When will it be delivered?","output":"It is expected to be delivered tomorrow."}
  ]
}

Session fields

Field

Logical type/Unit

Source and calculation

Purpose

sessionId

string

The selected result's session_id

Session lookup

startTimeMs

integer or null, Unix ms

The earliest start of all turns. The value is null if the time of any turn is unavailable.

Session start

endTimeMs

integer or null, Unix ms

The latest end of all turns. The value is null if the time of any turn is unavailable.

The end boundary of the currently returned range

durationMs

integer or null, ms

The latest end minus the earliest start

The session span, which is not equal to the active execution duration

turns

integer

The number of latest snapshots after business turn mapping. In this example, one logical trajectory is one turn.

The number of currently returned turns

totalTokens

integer or null

The sum of totalTokens of all turns. The value is null if any turn has a missing value.

The total usage of the currently returned turns

tokensComplete

boolean

Every turn has a valid, non-empty totalTokens value

Numeric presence. It does not prove that every model call reported usage.

timeComplete

boolean

The start and end of every turn have values, the start is positive, and the end is not earlier than the start

Time computability. It does not prove that the time comes from complete collection.

input

string

The input of the first turn after sorting

Session list summary

output

string

The output of the last turn after sorting

The summary of the answer in the most recent turn, which does not automatically indicate that the entire task succeeded

conversationTurns

Array of objects

Ordered turn summaries and snapshots

Turn-by-turn replay and tracing

These fields are generated by the SQL or application code in this topic for applications to store and consume. The business status, the collection coverage scope, and whether the query was truncated must be recorded separately.

Per-turn fields

Field

Logical type

Source and purpose

turn

integer

The display order starting from 1 in the current result. Late-arriving earlier turns change it.

sourceKind

string

snapshot.source_kind, which selects the Trace or Log decoding rules

trajectoryId

string

snapshot.trajectory_id, a stable execution reference

traceId

string, provided only for traces

snapshot.trace_id, used to look up the source spans

turnId

string, provided only for logs

snapshot.turn_id, the business turn ID of the source

startTimeMs, endTimeMs

integer or null

The numeric start and end of the source snapshot

durationMs

integer or null

end − start if the time is valid; otherwise, null

totalTokens

integer or null

The numeric snapshot.total_tokens, without adding sub-agents again

input, output

string

The text summary of the turn in the snapshot

snapshot

object

The complete trajectory fields that are currently selected. The field values retain the SLS string encoding.

snapshot.atif_content is still a JSON string and must be decoded again. Do not recursively try to parse plain text such as input/output. Embedded ATIF trajectories belong to the current turn and are not counted as separate session turns.

Generation order

  1. Determine the data space and source. The example in this topic targets one Logstore and one source type. If you work across tenants, applications, or Logstores, add the data space to the key. The Trace and Log representations of the same execution must not be billed twice.

  2. Read the required range. Make sure that the log time window covers the entire session and the related snapshots, and retrieve all required records. Do not filter by model or take the first N records and then claim a complete session.

  3. Select the latest snapshot. For the same source and trajectory_id, select the snapshot with the numerically largest process_time. Redeliveries that have the same time and the same business fields are treated as copies. Records that have the same time but different business content are treated as conflicts.

  4. Determine the session members. Group by session_id after you select the latest snapshots. This prevents the session membership of old snapshots from contaminating the result. The SQL in this example applies the session condition after latest.

  5. Map business turns and sort them. In this example, one logical trajectory is one turn, sorted by start_time in ascending order and then by trajectory_id in ascending order. Turns that have no start time are placed at the end. Sorting by ID for the same time only provides stable display and does not indicate causality.

  6. Retain the snapshots and summarize. Build the turn summaries, calculate the session min/max/count/sum, and take the input of the first turn and the output of the last turn. If the usage of any turn is missing, the total is null. Missing values are not silently filled with zero.

process_time is processed as an exact integer and must not be converted to a JavaScript Number before comparison. The version format ATIF-v1.7 does not participate in the ordering of results.

For a stored session, re-aggregate it after a late turn or a new trajectory snapshot arrives. The old snapshot of the same trajectory is replaced. Do not keep both the old and new tokens in the cumulative values. Applications can additionally store the query window, the generation time, and the coverage status, but this information does not prove that the business has ended.

Scan SQL

When the scan index is enabled, you can use scan SQL to read the complete fields and directly build a session that contains complete snapshots. Use set session mode=scan; explicitly in a standalone statement. You do not need to enable regular statistics indexes for every analyzed field. Pre-filtering by index still requires the corresponding indexes. For more information, see Syntax of scan-based analysis.

The appendix of this topic contains the complete SQL. When you use it:

  • Replace source_kind = 'otel_trace' with the required source. For logs, use otel_log.

  • Replace session_id = 'session-demo-001' with the target session, and set the complete log time range on the caller side.

  • The SQL enumerates all 47 distinct business fields of the two sources in this topic and four storage metadata fields. Fields that do not exist in a source are omitted, and existing empty strings are retained.

  • When you add a schema field, update the key-value list of snapshot accordingly. Scan reads do not automatically add fields that are not enumerated in the query.

  • The result session_json is JSON text. Parse it once to obtain the session. Consume the result only when aggregation_error is empty. An equal-version conflict returns conflicting_latest_snapshot, and an invalid latest identity/timestamp or negative tokens return invalid_latest_snapshot. In these cases, session_json is null.

  • If no session matches, zero rows are returned. A strict CAST of an invalid number can cause an SQL error. In this case, locate the source value. Do not treat the error result as an empty session.

When you use the query API, also check whether the request is complete, whether the result is exact, and whether the full range and all pages are retrieved. A successful query only proves that this request is complete, and tokensComplete/timeComplete also checks only the conditions defined in the tables of this topic.

Application-side generation

Download the sample package from Sample data and usage code, decompress it, and then go to the package directory. scripts/session_view.py depends only on the Python 3 standard library, accepts the complete result array of the same data space, and retains all raw fields:

python3 scripts/session_view.py examples/trajectory-history.json \
  --session-id session-demo-001 --source-kind otel_trace

trajectory-history.json contains the old snapshot of the first turn, the latest snapshots, and duplicate deliveries. The script result is still 2 turns and 205 tokens, which is consistent with session.json. When you connect real data, replace the input file with the complete array of trajectory records obtained from the query.

build_session returns None if no data matches, which corresponds to JSON null on the command line. An exception is thrown if a business content conflict is found in the same latest version. The packaging metadata of different copies is not used to determine business content conflicts.

Appendix: Complete SQL

* | set session mode=scan;
WITH raw_values AS (
    SELECT
        session_id, trajectory_id, source_kind, trace_id, turn_id, input, output,
        CAST(NULLIF(CAST(start_time AS varchar), '') AS bigint) AS start_ms,
        CAST(NULLIF(CAST(end_time AS varchar), '') AS bigint) AS end_ms,
        CAST(NULLIF(CAST(total_tokens AS varchar), '') AS bigint) AS token_count,
        CAST(NULLIF(CAST(process_time AS varchar), '') AS bigint) AS process_ns,
        __time__ AS log_time,
        CAST(map_filter(map(
            ARRAY[
                'trajectory_id',
                'trace_id',
                'source_kind',
                'session_id',
                'turn_id',
                'version',
                'degraded',
                'degraded_reason',
                'input_empty_reason',
                'start_time',
                'end_time',
                'process_time',
                'duration_ms',
                'input',
                'output',
                'atif_content',
                'trajectory_extensions',
                'agent_name',
                'agent_version',
                'agent_attributes',
                'service_names',
                'step_count',
                'total_tokens',
                'input_tokens',
                'output_tokens',
                'cached_tokens',
                'total_cost',
                'model_calls',
                'model_call_count',
                'models',
                'tool_calls',
                'tool_call_count',
                'tool_names',
                'tool_errors',
                'skills',
                'skill_call_count',
                'skill_ids',
                'skill_names',
                'has_sub_agent',
                'sub_agent_count',
                'subagent_trajectory_ids',
                'output_modalities',
                'output_artifacts',
                'agent_names',
                'trajectory_relationships',
                'custom_fields',
                'custom_fields_status',
                '__time__',
                '__topic__',
                '__source__',
                '__pack_meta__'
            ],
            ARRAY[
                CAST("trajectory_id" AS varchar),
                CAST("trace_id" AS varchar),
                CAST("source_kind" AS varchar),
                CAST("session_id" AS varchar),
                CAST("turn_id" AS varchar),
                CAST("version" AS varchar),
                CAST("degraded" AS varchar),
                CAST("degraded_reason" AS varchar),
                CAST("input_empty_reason" AS varchar),
                CAST("start_time" AS varchar),
                CAST("end_time" AS varchar),
                CAST("process_time" AS varchar),
                CAST("duration_ms" AS varchar),
                CAST("input" AS varchar),
                CAST("output" AS varchar),
                CAST("atif_content" AS varchar),
                CAST("trajectory_extensions" AS varchar),
                CAST("agent_name" AS varchar),
                CAST("agent_version" AS varchar),
                CAST("agent_attributes" AS varchar),
                CAST("service_names" AS varchar),
                CAST("step_count" AS varchar),
                CAST("total_tokens" AS varchar),
                CAST("input_tokens" AS varchar),
                CAST("output_tokens" AS varchar),
                CAST("cached_tokens" AS varchar),
                CAST("total_cost" AS varchar),
                CAST("model_calls" AS varchar),
                CAST("model_call_count" AS varchar),
                CAST("models" AS varchar),
                CAST("tool_calls" AS varchar),
                CAST("tool_call_count" AS varchar),
                CAST("tool_names" AS varchar),
                CAST("tool_errors" AS varchar),
                CAST("skills" AS varchar),
                CAST("skill_call_count" AS varchar),
                CAST("skill_ids" AS varchar),
                CAST("skill_names" AS varchar),
                CAST("has_sub_agent" AS varchar),
                CAST("sub_agent_count" AS varchar),
                CAST("subagent_trajectory_ids" AS varchar),
                CAST("output_modalities" AS varchar),
                CAST("output_artifacts" AS varchar),
                CAST("agent_names" AS varchar),
                CAST("trajectory_relationships" AS varchar),
                CAST("custom_fields" AS varchar),
                CAST("custom_fields_status" AS varchar),
                CAST("__time__" AS varchar),
                CAST("__topic__" AS varchar),
                CAST("__source__" AS varchar),
                CAST("__pack_meta__" AS varchar)
            ]
        ), (k, v) -> v IS NOT NULL) AS JSON) AS snapshot_json
    FROM log
    WHERE source_kind = 'otel_trace'
), encoded AS (
    SELECT *, json_format(CAST(map_filter(
        CAST(snapshot_json AS map(varchar, json)),
        (k, v) -> NOT starts_with(k, '__')
    ) AS JSON)) AS business_json
    FROM raw_values
), ranked AS (
    SELECT *, DENSE_RANK() OVER (
        PARTITION BY source_kind, trajectory_id
        ORDER BY process_ns DESC NULLS LAST
    ) AS version_rank
    FROM encoded
), heads AS (
    SELECT * FROM ranked WHERE version_rank = 1
), conflicting_ids AS (
    SELECT source_kind, trajectory_id
    FROM heads
    GROUP BY source_kind, trajectory_id
    HAVING count(DISTINCT business_json) > 1
), session_heads AS (
    SELECT * FROM heads WHERE session_id = 'session-demo-001'
), integrity AS (
    SELECT count_if(process_ns IS NULL OR process_ns <= 0
                    OR trajectory_id IS NULL OR trajectory_id = ''
                    OR token_count < 0) AS invalid_heads
    FROM session_heads
), conflicts AS (
    SELECT count(*) AS conflict_count
    FROM conflicting_ids c
    JOIN (SELECT DISTINCT source_kind, trajectory_id FROM session_heads) s
      ON c.source_kind = s.source_kind AND c.trajectory_id = s.trajectory_id
), copies AS (
    SELECT *, ROW_NUMBER() OVER (
        PARTITION BY source_kind, trajectory_id
        ORDER BY log_time DESC, json_format(snapshot_json) DESC
    ) AS copy_rank
    FROM session_heads
), numbered AS (
    SELECT *, ROW_NUMBER() OVER (
        ORDER BY start_ms ASC NULLS LAST, trajectory_id ASC
    ) AS turn_no
    FROM copies WHERE copy_rank = 1
), turns AS (
    SELECT *, CAST(map_filter(map(
        ARRAY['turn', 'sourceKind', 'traceId', 'turnId', 'trajectoryId',
              'startTimeMs', 'endTimeMs', 'durationMs', 'totalTokens',
              'input', 'output', 'snapshot'],
        ARRAY[
            CAST(turn_no AS JSON), CAST(source_kind AS JSON),
            CAST(trace_id AS JSON), CAST(turn_id AS JSON), CAST(trajectory_id AS JSON),
            CAST(start_ms AS JSON), CAST(end_ms AS JSON),
            CAST(CASE WHEN start_ms > 0 AND end_ms >= start_ms THEN end_ms - start_ms END AS JSON),
            CAST(token_count AS JSON), CAST(input AS JSON), CAST(output AS JSON), snapshot_json
        ]
    ), (k, v) -> k NOT IN ('traceId', 'turnId') OR v IS NOT NULL) AS JSON) AS turn_json
    FROM numbered
), grouped AS (
    SELECT session_id, min(start_ms) AS session_start, max(end_ms) AS session_end,
        count(*) AS turn_count,
        CASE WHEN count(token_count) = count(*) THEN sum(token_count) END AS tokens,
        count(token_count) = count(*) AS tokens_complete,
        count(start_ms) = count(*) AND count(end_ms) = count(*)
          AND count_if(start_ms <= 0 OR end_ms < start_ms) = 0 AS time_complete,
        min_by(input, turn_no) AS first_input, max_by(output, turn_no) AS last_output,
        array_sort(array_agg(turn_no)) AS turn_order,
        map_agg(turn_no, turn_json) AS turn_map
    FROM turns GROUP BY session_id
)
SELECT CASE WHEN invalid_heads > 0 OR conflict_count > 0 THEN NULL
    ELSE json_format(CAST(map(
        ARRAY['sessionId', 'startTimeMs', 'endTimeMs', 'durationMs', 'turns',
              'totalTokens', 'tokensComplete', 'timeComplete', 'input', 'output', 'conversationTurns'],
        ARRAY[
            CAST(session_id AS JSON),
            CAST(CASE WHEN time_complete THEN session_start END AS JSON),
            CAST(CASE WHEN time_complete THEN session_end END AS JSON),
            CAST(CASE WHEN time_complete THEN session_end - session_start END AS JSON),
            CAST(turn_count AS JSON), CAST(tokens AS JSON),
            CAST(tokens_complete AS JSON), CAST(time_complete AS JSON),
            CAST(first_input AS JSON), CAST(last_output AS JSON),
            CAST(transform(turn_order, n -> element_at(turn_map, n)) AS JSON)
        ]
    ) AS JSON)) END AS session_json,
    CASE WHEN invalid_heads > 0 THEN 'invalid_latest_snapshot'
         WHEN conflict_count > 0 THEN 'conflicting_latest_snapshot'
         ELSE '' END AS aggregation_error
FROM grouped CROSS JOIN integrity CROSS JOIN conflicts
LIMIT 100