Skip to content

Commit d20d023

Browse files
committed
fix(ingest): bound JSON flattening rows and expanded bytes
1 parent 04b73b5 commit d20d023

24 files changed

Lines changed: 5805 additions & 194 deletions

‎docs/json-flattening-limits.md‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# JSON flattening limits
2+
3+
Generic flattening turns every nested array of an event into rows: an event becomes one row
4+
for each combination of the values of its arrays. Sibling arrays multiply, so
5+
`{"a": [0..999], "b": [0..999], "c": [0..999]}`, about 11 KiB of JSON, would expand into
6+
10^9 rows. Three limits cap that expansion. Parseable checks them before it builds any row,
7+
and rejects the whole request with `400 Bad Request` when one is exceeded. Nothing from a
8+
rejected request is ingested.
9+
10+
| Environment variable | Flag | Default | Limit |
11+
| --------------------------------- | --------------------------------- | -------------------- | --------------------------------------------------------- |
12+
| `P_MAX_FLATTEN_ROWS_PER_EVENT` | `--max-flatten-rows-per-event` | `1000` | Rows a single event may expand into |
13+
| `P_MAX_FLATTEN_ROWS_PER_REQUEST` | `--max-flatten-rows-per-request` | `10000` | Rows all events of one request may expand into together |
14+
| `P_MAX_FLATTEN_BYTES_PER_REQUEST` | `--max-flatten-bytes-per-request` | `67108864` (64 MiB) | Bytes all those rows may add up to, measured as compact JSON |
15+
16+
Each value must be a positive integer. A limit cannot be set to zero or switched off.
17+
18+
The byte limit counts the size of the expanded rows as compact JSON, including keys,
19+
quotes, escapes and delimiters. It also counts what is copied into every row afterwards:
20+
Kinesis request metadata and OTEL body key prefixes (see below). It is not a measure of the
21+
memory a request uses.
22+
23+
After generic flattening, every row is flattened structurally: nested objects become fields
24+
named after the keys on their path, joined with `_`. A parent's name is repeated in every
25+
field below it, so `{"<128 character name>": {"f0": 0, ..., "f31": 31}, "r": [0, 1, 2, 3]}`
26+
expands into 4 rows of about 400 bytes, but each of them structurally flattened takes about
27+
4.4 KiB. Every event is therefore charged the larger of the two: the compact JSON of its
28+
generic rows, or of those rows structurally flattened. Both are computed in one pass over
29+
the event, before any row or field name is built. The structurally flattened size counts
30+
every scalar as a field of its own, even when its joined name collides with another field
31+
(for example `{"a_b": 1, "a": {"b": 2}}`, where one `a_b` overwrites the other), so with
32+
such collisions it is an overestimate. Empty objects add no field.
33+
34+
## What counts as an event
35+
36+
The limits apply only where generic flattening runs:
37+
38+
- **JSON and custom sources** (`/api/v1/ingest`, `/api/v1/logstream/{name}`) on datasets using
39+
schema version V1. Every object in the request body is one event, after any nested
40+
top-level arrays are spliced in. Bodies nested deeper than `P_MAX_FLATTEN_LEVEL` skip
41+
generic flattening, so these limits do not apply to them.
42+
- **Kinesis**: every decoded `data` record is one event, even when it holds a JSON array.
43+
Each of its rows also gets the request's `requestId` and `timestamp`, so their compact
44+
JSON size, with keys and delimiters, is counted once per row, on top of the larger of the
45+
generic and structurally flattened sizes. It is counted in full even for rows that
46+
already have these fields.
47+
- **OTEL logs**: a log record whose body (or a body field) is a string holding a JSON object
48+
has that object flattened. All flattened bodies of one log record together are one event.
49+
This counts every intermediate row, even though the rows end up merged into the single
50+
log record. Each top-level field of a flattened body is renamed to `{body key}_{field}`
51+
before the merge, so the body key, with its escapes and the `_`, is counted again for
52+
every such field in every row. Structurally flattening the record afterwards repeats the
53+
body key in the name of every field nested below those too, `{body key}_{field}_{name}`.
54+
A body is charged the larger of its generic rows with the renamed top-level fields, or
55+
of its structurally flattened rows with the body key in every field name. This counts
56+
the rows of a body as if they were all kept, though only the last value of each field
57+
ends up in the record.
58+
- **Schema detection** (`/api/v1/logstream/schema/detect`) counts the request body the same
59+
way as JSON ingestion, structurally flattened rows included.
60+
61+
Every request has a budget of its own. All events of a request share that budget, across
62+
custom partition elements, Kinesis records, and OTEL resources and scopes. OTEL metrics and
63+
traces, Kafka, and V0 datasets do not use generic flattening, so these limits do not apply
64+
to them.
65+
66+
Internal dataset statistics (`pstats`) use the configured byte limit. Their row limits come
67+
from the size of the stats payload, which is the field count times `P_MAX_FIELD_STATISTICS`.
68+
69+
## When a request is rejected
70+
71+
The error message names the limit that was exceeded and its value. To get under the limit,
72+
reduce the number or length of the nested arrays in each event, or split the batch into
73+
smaller requests. You can also raise the limit.
74+
75+
`tools/flatten-bench/http_smoke.py` checks these responses against a built server binary.

‎src/cli.rs‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ pub const DEFAULT_USERNAME: &str = "admin";
3636
pub const DEFAULT_PASSWORD: &str = "admin";
3737

3838
pub const DATASET_FIELD_COUNT_LIMIT: usize = 1000;
39+
pub const DEFAULT_MAX_FLATTEN_ROWS_PER_EVENT: usize = 1000;
40+
pub const DEFAULT_MAX_FLATTEN_ROWS_PER_REQUEST: usize = 10_000;
41+
pub const DEFAULT_MAX_FLATTEN_BYTES_PER_REQUEST: usize = 64 * 1024 * 1024;
3942
const DEFAULT_PARQUET_METADATA_CACHE_SIZE: usize = 50 * 1024 * 1024; // 50 MB
4043
#[derive(Parser)]
4144
#[command(
@@ -640,6 +643,35 @@ pub struct Options {
640643
)]
641644
pub max_event_payload_size: usize,
642645

646+
// generic flattening expands nested arrays into the cartesian product of their values,
647+
// these bound that expansion for JSON/custom sources, Kinesis and OTEL log bodies
648+
#[arg(
649+
long,
650+
env = "P_MAX_FLATTEN_ROWS_PER_EVENT",
651+
default_value_t = DEFAULT_MAX_FLATTEN_ROWS_PER_EVENT,
652+
value_parser = validation::validate_flatten_limit,
653+
help = "Maximum number of rows a single event may expand into when its nested arrays are flattened"
654+
)]
655+
pub max_flatten_rows_per_event: usize,
656+
657+
#[arg(
658+
long,
659+
env = "P_MAX_FLATTEN_ROWS_PER_REQUEST",
660+
default_value_t = DEFAULT_MAX_FLATTEN_ROWS_PER_REQUEST,
661+
value_parser = validation::validate_flatten_limit,
662+
help = "Maximum number of rows all events of an ingest request may expand into when their nested arrays are flattened"
663+
)]
664+
pub max_flatten_rows_per_request: usize,
665+
666+
#[arg(
667+
long,
668+
env = "P_MAX_FLATTEN_BYTES_PER_REQUEST",
669+
default_value_t = DEFAULT_MAX_FLATTEN_BYTES_PER_REQUEST,
670+
value_parser = validation::validate_flatten_limit,
671+
help = "Maximum total size in bytes of the rows, measured as compact JSON, that all events of an ingest request may expand into when their nested arrays are flattened. This is not a bound on the memory used"
672+
)]
673+
pub max_flatten_bytes_per_request: usize,
674+
643675
#[arg(
644676
long,
645677
env = "P_NORMALISE_OTEL_PAYLOAD",

‎src/handlers/http/ingest.rs‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -562,6 +562,8 @@ impl actix_web::ResponseError for PostError {
562562
| CreateStream(CreateStreamError::StreamNameValidation(_))
563563
| OtelNotSupported(_) => StatusCode::BAD_REQUEST,
564564

565+
JsonFlattenError(e) if e.is_limit_exceeded() => StatusCode::BAD_REQUEST,
566+
565567
Event(_)
566568
| CreateStream(_)
567569
| CustomError(_)
@@ -1129,4 +1131,31 @@ mod tests {
11291131
&Float64Array::from(vec![None, None, None, Some(2.0)])
11301132
);
11311133
}
1134+
1135+
#[test]
1136+
fn flatten_limit_errors_are_bad_requests() {
1137+
use actix_web::{ResponseError, http::StatusCode};
1138+
1139+
use super::PostError;
1140+
use crate::utils::json::flatten::JsonFlattenError;
1141+
1142+
for limit in [
1143+
JsonFlattenError::RowsPerEventLimitExceeded(1000),
1144+
JsonFlattenError::RowsPerRequestLimitExceeded(10_000),
1145+
JsonFlattenError::BytesPerRequestLimitExceeded(64),
1146+
] {
1147+
let message = limit.to_string();
1148+
let error = PostError::JsonFlattenError(limit);
1149+
assert_eq!(error.status_code(), StatusCode::BAD_REQUEST);
1150+
assert!(error.to_string().contains(&message));
1151+
}
1152+
// Limit errors from the JSON and Kinesis paths arrive wrapped in anyhow
1153+
let error = PostError::Invalid(JsonFlattenError::RowsPerEventLimitExceeded(1).into());
1154+
assert_eq!(error.status_code(), StatusCode::BAD_REQUEST);
1155+
// Other flatten errors keep their status
1156+
assert_eq!(
1157+
PostError::JsonFlattenError(JsonFlattenError::ExpectedObjectInArray).status_code(),
1158+
StatusCode::INTERNAL_SERVER_ERROR
1159+
);
1160+
}
11321161
}

0 commit comments

Comments
 (0)