Skip to content

Commit bbd64a0

Browse files
authored
fix(projection): validate canonical decimal timestamps in TypeScript hrTime and skip non-finite floats in spanAttributes (#119)
Closes #114 ### Summary - Validate canonical non-negative decimal strings (`/^(0|[1-9][0-9]{0,19})$/`) and safe-integer seconds in TypeScript `hrTime` (`packages/typescript/src/projection.ts`) before calling `BigInt(value)`. - Skip non-finite `float`/`number` values (`NaN`, `Infinity`) in `span_attributes` (`src/agentrust_telemetry/projection.py`) and `spanAttributes` (`packages/typescript/src/projection.ts`). - Add Python and TypeScript unit tests in `tests/test_otel_projectors.py` and `packages/typescript/test/metrics.test.ts`. ### Validation - `pytest tests/test_otel_projectors.py -k "not real and not action_metrics" -q` — passed (`4 passed`) Signed-off-by: Raghuvar Karthik Durga <177662415+drk-ram@users.noreply.github.com> Co-authored-by: Raghuvar Karthik Durga <177662415+drk-ram@users.noreply.github.com>
1 parent 93c14fc commit bbd64a0

8 files changed

Lines changed: 223 additions & 1 deletion

File tree

‎conformance/parity/README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Projection boundary corpus
2+
3+
Both SDK test suites consume projection-boundaries.json. This slice covers six canonical timestamps, thirteen noncanonical spellings, and five scalar projection cases. Nonfinite values use local special-value tags because they have no JSON representation. These projection inputs are not assertions that arbitrary event fields pass the event schema.
4+
5+
This companion is based on telemetry #119. Other adapter timestamp/duration and EventFactory corrections remain in #116–120; it neither replaces those fixes nor claims their acceptance. The 20-digit tuple is an explicit positive boundary; logs, delivery, collector behavior and hardware are separate.
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
{
2+
"timestamps": [
3+
{
4+
"input": "0",
5+
"tuple": [
6+
0,
7+
0
8+
]
9+
},
10+
{
11+
"input": "1",
12+
"tuple": [
13+
0,
14+
1
15+
]
16+
},
17+
{
18+
"input": "999999999",
19+
"tuple": [
20+
0,
21+
999999999
22+
]
23+
},
24+
{
25+
"input": "1000000000",
26+
"tuple": [
27+
1,
28+
0
29+
]
30+
},
31+
{
32+
"input": "1000000001",
33+
"tuple": [
34+
1,
35+
1
36+
]
37+
},
38+
{
39+
"input": "99999999999999999999",
40+
"tuple": [
41+
99999999999,
42+
999999999
43+
]
44+
}
45+
],
46+
"invalid_timestamps": [
47+
"",
48+
" ",
49+
"-1",
50+
"+1",
51+
"01",
52+
"0x10",
53+
"1.0",
54+
"1e9",
55+
"1\n",
56+
"1\r",
57+
"1
",
58+
"١",
59+
"111111111111111111111"
60+
],
61+
"projections": [
62+
{
63+
"id": "finite-scalars",
64+
"event": {
65+
"run_id": "run-1",
66+
"task_id": 0,
67+
"decision": false
68+
},
69+
"expected": {
70+
"agentrust.run.id": "run-1",
71+
"agentrust.task.id": 0,
72+
"agentrust.policy.decision": false
73+
}
74+
},
75+
{
76+
"id": "structured-and-null-omit",
77+
"event": {
78+
"run_id": "run-1",
79+
"task_id": null,
80+
"workflow_id": [],
81+
"agent_id": {}
82+
},
83+
"expected": {
84+
"agentrust.run.id": "run-1"
85+
}
86+
},
87+
{
88+
"id": "unmapped-payload-omit",
89+
"event": {
90+
"run_id": "run-1",
91+
"payload": "synthetic"
92+
},
93+
"expected": {
94+
"agentrust.run.id": "run-1"
95+
}
96+
},
97+
{
98+
"id": "nonfinite-omit",
99+
"event": {
100+
"run_id": "run-1"
101+
},
102+
"special": {
103+
"task_id": "nan",
104+
"workflow_id": "positive_infinity",
105+
"agent_id": "negative_infinity"
106+
},
107+
"expected": {
108+
"agentrust.run.id": "run-1"
109+
}
110+
},
111+
{
112+
"id": "fractional-scalar",
113+
"event": {
114+
"run_id": "run-1",
115+
"task_id": 1.5
116+
},
117+
"expected": {
118+
"agentrust.run.id": "run-1",
119+
"agentrust.task.id": 1.5
120+
}
121+
}
122+
]
123+
}

‎packages/typescript/src/projection.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ export function spanAttributes(event: NormalizedEvent): Record<string, Scalar> {
1414
const result: Record<string, Scalar> = {};
1515
for (const [source, destination] of Object.entries(DIRECT_ATTRIBUTES)) {
1616
const value = event[source];
17+
if (typeof value === "number" && !Number.isFinite(value)) continue;
1718
if (["string", "number", "boolean"].includes(typeof value)) result[destination] = value as Scalar;
1819
}
1920
return result;
@@ -22,5 +23,9 @@ export function logRecord(event: NormalizedEvent, context?: ContextIds): Record<
2223
return {event_name: event.event_type, timestamp_ns: event.time_unix_nano, body: structuredClone(event), ...(context ? {trace_id: context.traceId, span_id: context.spanId} : {})};
2324
}
2425
export function hrTime(value: string): [number, number] {
25-
const timestamp = BigInt(value); return [Number(timestamp / 1_000_000_000n), Number(timestamp % 1_000_000_000n)];
26+
if (typeof value !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(value)) throw new Error("Unix nanosecond timestamps must be canonical non-negative decimals of at most 20 digits");
27+
const timestamp = BigInt(value);
28+
const seconds = timestamp / 1_000_000_000n;
29+
if (seconds > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error("timestamp seconds exceed safe integer range");
30+
return [Number(seconds), Number(timestamp % 1_000_000_000n)];
2631
}

‎packages/typescript/test/metrics.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,12 @@ test("policy, approval, and action metrics expose only bounded semantic dimensio
3434
for (const name of ["policy-decision.json", "approval.json", "action.json"]) assert.equal(emitter.emit(fixture(name)), true);
3535
assert.deepEqual(Object.keys(meter.instruments.get("agentrust.action.executions")!.calls[0]!.attributes!).sort(), ["agentrust.action.kind", "agentrust.action.outcome"]);
3636
});
37+
38+
test("hrTime rejects malformed timestamps and spanAttributes skips non-finite numbers", async () => {
39+
const {hrTime, spanAttributes} = await import("../src/projection.js");
40+
for (const bad of ["", " ", "-1", "0x10", "01", "1".repeat(21)]) {
41+
assert.throws(() => hrTime(bad), /canonical non-negative decimals/);
42+
}
43+
const attrs = spanAttributes({run_id: "r1", task_id: Number.NaN, workflow_id: Number.POSITIVE_INFINITY} as unknown as NormalizedEvent);
44+
assert.deepEqual(attrs, {"agentrust.run.id": "r1"});
45+
});
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import assert from "node:assert/strict";
2+
import {readFileSync} from "node:fs";
3+
import test from "node:test";
4+
import {hrTime, spanAttributes} from "../src/projection.js";
5+
import type {NormalizedEvent} from "../src/types.js";
6+
7+
const corpus = JSON.parse(readFileSync(
8+
new URL("../../../conformance/parity/projection-boundaries.json", import.meta.url), "utf8",
9+
));
10+
for (const row of corpus.timestamps) {
11+
test("shared timestamp " + row.input, () => assert.deepEqual(hrTime(row.input), row.tuple));
12+
}
13+
for (const value of corpus.invalid_timestamps) {
14+
test("shared noncanonical timestamp " + JSON.stringify(value), () => {
15+
assert.throws(() => hrTime(value));
16+
});
17+
}
18+
const special: Record<string, number> = {
19+
nan: Number.NaN, positive_infinity: Number.POSITIVE_INFINITY,
20+
negative_infinity: Number.NEGATIVE_INFINITY,
21+
};
22+
for (const row of corpus.projections) {
23+
test("shared scalar projection " + row.id, () => {
24+
const event = {...row.event};
25+
for (const [key, value] of Object.entries(row.special ?? {})) {
26+
event[key] = special[value as string];
27+
}
28+
assert.deepEqual(spanAttributes(event as NormalizedEvent), row.expected);
29+
});
30+
}

‎src/agentrust_telemetry/projection.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from __future__ import annotations
44

55
from copy import deepcopy
6+
import math
67
from typing import Any
78

89
from .context import ContextIds
@@ -32,6 +33,8 @@ def span_attributes(event: dict[str, Any]) -> dict[str, str | int | float | bool
3233
projected: dict[str, str | int | float | bool] = {}
3334
for source, destination in DIRECT_ATTRIBUTES.items():
3435
value = event.get(source)
36+
if isinstance(value, float) and not math.isfinite(value):
37+
continue
3538
if isinstance(value, (str, int, float, bool)):
3639
projected[destination] = value
3740
return projected

‎tests/test_otel_projectors.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,18 @@ def test_action_metrics_exclude_action_and_agent_identifiers(self):
163163
{"agentrust.action.kind", "agentrust.action.outcome"},
164164
)
165165

166+
def test_span_attributes_excludes_nonfinite_floats(self):
167+
from agentrust_telemetry.projection import span_attributes
168+
169+
attrs = span_attributes(
170+
{
171+
"run_id": "r-1",
172+
"task_id": float("nan"),
173+
"workflow_id": float("inf"),
174+
}
175+
)
176+
self.assertEqual(attrs, {"agentrust.run.id": "r-1"})
177+
166178

167179
if __name__ == "__main__":
168180
unittest.main()
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""Shared Python/TypeScript normalization and projection cases, not schema acceptance."""
2+
import json
3+
import math
4+
import unittest
5+
from pathlib import Path
6+
7+
from agentrust_telemetry.adapters.base import _unix_nano
8+
from agentrust_telemetry.projection import span_attributes
9+
10+
CORPUS = json.loads(
11+
(Path(__file__).resolve().parents[1] / "conformance/parity/projection-boundaries.json")
12+
.read_text(encoding="utf-8")
13+
)
14+
15+
16+
class TestProjectionParityCorpus(unittest.TestCase):
17+
def test_timestamp_normalization(self):
18+
for case in CORPUS["timestamps"]:
19+
with self.subTest(value=case["input"]):
20+
normalized = _unix_nano(case["input"])
21+
self.assertEqual(normalized, case["input"])
22+
self.assertEqual(list(divmod(int(normalized), 1_000_000_000)), case["tuple"])
23+
24+
def test_noncanonical_timestamps(self):
25+
for value in CORPUS["invalid_timestamps"]:
26+
with self.subTest(value=value), self.assertRaises((ValueError, TypeError)):
27+
_unix_nano(value)
28+
29+
def test_scalar_projection(self):
30+
special = {"nan": math.nan, "positive_infinity": math.inf, "negative_infinity": -math.inf}
31+
for case in CORPUS["projections"]:
32+
with self.subTest(case=case["id"]):
33+
event = dict(case["event"])
34+
event.update({key: special[value] for key, value in case.get("special", {}).items()})
35+
self.assertEqual(span_attributes(event), case["expected"])

0 commit comments

Comments
 (0)