Skip to content

Commit 7fe8a17

Browse files
committed
fix(stats): stream bounded rows and clarify ingest limits
1 parent d20d023 commit 7fe8a17

13 files changed

Lines changed: 816 additions & 198 deletions

File tree

‎docs/json-flattening-limits.md‎

Lines changed: 99 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,17 @@
33
Generic flattening turns every nested array of an event into rows: an event becomes one row
44
for each combination of the values of its arrays. Sibling arrays multiply, so
55
`{"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.
6+
10^9 rows. Three limits cap that expansion.
7+
8+
Parseable checks each event against the limits before it builds the rows of that event: it
9+
counts the rows and bytes the event expands into without building them. When an event would
10+
go over a limit, the whole request is rejected with `400 Bad Request`. None of its events
11+
are stored, and none of its fields are added to the dataset schema. Events that came before
12+
it in the same request may already have been expanded in memory by then, within the
13+
limits, and are dropped with the rest: in a dataset with a custom or time partition, and
14+
for Kinesis and OTEL, the events of a request are expanded one after the other. An
15+
endpoint that creates the dataset on first use, such as `/api/v1/ingest`, does that before
16+
it flattens the request, so a rejected request can still leave a new, empty dataset.
917

1018
| Environment variable | Flag | Default | Limit |
1119
| --------------------------------- | --------------------------------- | -------------------- | --------------------------------------------------------- |
@@ -15,37 +23,47 @@ rejected request is ingested.
1523

1624
Each value must be a positive integer. A limit cannot be set to zero or switched off.
1725

26+
These limits are new, and they reject some requests that earlier versions accepted,
27+
including batches of small events without any arrays. Read
28+
[Upgrading](#upgrading-requests-that-are-now-rejected) before you upgrade.
29+
1830
The byte limit counts the size of the expanded rows as compact JSON, including keys,
1931
quotes, escapes and delimiters. It also counts what is copied into every row afterwards:
2032
Kinesis request metadata and OTEL body key prefixes (see below). It is not a measure of the
21-
memory a request uses.
33+
memory a request uses. It is independent of `P_MAX_EVENT_PAYLOAD_SIZE` (10 MiB by default,
34+
at most 100 MiB), which limits the size of the request body as it is received: a request
35+
within one of them can be over the other.
2236

2337
After generic flattening, every row is flattened structurally: nested objects become fields
2438
named after the keys on their path, joined with `_`. A parent's name is repeated in every
2539
field below it, so `{"<128 character name>": {"f0": 0, ..., "f31": 31}, "r": [0, 1, 2, 3]}`
2640
expands into 4 rows of about 400 bytes, but each of them structurally flattened takes about
2741
4.4 KiB. Every event is therefore charged the larger of the two: the compact JSON of its
2842
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.
43+
the event, before any row or field name of it is built. The structurally flattened size
44+
counts every scalar as a field of its own, even when its joined name collides with another
45+
field (for example `{"a_b": 1, "a": {"b": 2}}`, where one `a_b` overwrites the other), so
46+
with such collisions it is an overestimate. Empty objects add no field.
3347

3448
## What counts as an event
3549

36-
The limits apply only where generic flattening runs:
50+
The limits apply only where generic flattening runs. There, every event takes at least one
51+
row, including an event without arrays, which generic flattening leaves as it is:
3752

3853
- **JSON and custom sources** (`/api/v1/ingest`, `/api/v1/logstream/{name}`) on datasets using
3954
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.
55+
top-level arrays are spliced in, so a batch (a top-level array) of 10,001 objects takes at
56+
least 10,001 rows. Bodies nested deeper than `P_MAX_FLATTEN_LEVEL` skip generic
57+
flattening, so these limits do not apply to them.
4258
- **Kinesis**: every decoded `data` record is one event, even when it holds a JSON array.
4359
Each of its rows also gets the request's `requestId` and `timestamp`, so their compact
4460
JSON size, with keys and delimiters, is counted once per row, on top of the larger of the
4561
generic and structurally flattened sizes. It is counted in full even for rows that
46-
already have these fields.
62+
already have these fields. A record nested deeper than `P_MAX_FLATTEN_LEVEL` is ingested
63+
as it is, and not counted.
4764
- **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.
65+
has that object flattened. All flattened bodies of one log record together are one event,
66+
of at least one row per flattened body. A log record without such a body takes no rows.
4967
This counts every intermediate row, even though the rows end up merged into the single
5068
log record. Each top-level field of a flattened body is renamed to `{body key}_{field}`
5169
before the merge, so the body key, with its escapes and the `_`, is counted again for
@@ -61,15 +79,78 @@ The limits apply only where generic flattening runs:
6179
Every request has a budget of its own. All events of a request share that budget, across
6280
custom partition elements, Kinesis records, and OTEL resources and scopes. OTEL metrics and
6381
traces, Kafka, and V0 datasets do not use generic flattening, so these limits do not apply
64-
to them.
82+
to them. Internal dataset statistics are bounded differently, see
83+
[below](#internal-dataset-statistics-pstats).
84+
85+
## Upgrading: requests that are now rejected
86+
87+
Earlier versions flattened every event without a limit. With the defaults, these requests
88+
are now rejected:
89+
90+
- **More than 10,000 events in one request.** Every event counts toward
91+
`P_MAX_FLATTEN_ROWS_PER_REQUEST`, including an event without arrays. A JSON batch of
92+
10,001 `{"a":1}` events is about 80 KB, far below the 10 MiB default of
93+
`P_MAX_EVENT_PAYLOAD_SIZE`, and it is rejected. So is a Kinesis request of more than
94+
10,000 records, an OTEL logs request of more than 10,000 log records with JSON object
95+
bodies, and schema detection of more than 10,000 events. Shippers that batch by size or
96+
by time, rather than by a number of events, can send such requests.
97+
- **More than 1,000 values in an array of one event.** An event such as `{"items": [...]}`
98+
with 1,001 items expands into 1,001 rows, over `P_MAX_FLATTEN_ROWS_PER_EVENT`. That
99+
includes an event that wraps its records in an array, like `{"records": [...]}`, and a
100+
Kinesis record that decodes to an array of more than 1,000 objects. The elements of a
101+
top-level array in a request body are events of their own, so this limit does not apply
102+
to a top-level array (the limit per request does).
103+
- **Rows over 64 MiB in one request.** For a JSON batch of events without arrays or nested
104+
objects, the rows take about the size of the batch without whitespace. With the 10 MiB
105+
default of `P_MAX_EVENT_PAYLOAD_SIZE`, such batches stay well below
106+
`P_MAX_FLATTEN_BYTES_PER_REQUEST`; they can reach it once `P_MAX_EVENT_PAYLOAD_SIZE` is
107+
raised close to or above 64 MiB. Nested arrays, and parent names repeated in the
108+
structurally flattened field names, make the rows larger than the request.
109+
110+
Nothing is truncated: a request over a limit is rejected whole, with a `400` that names the
111+
limit, and no part of it is stored. Many shippers treat a `400` as permanent and drop the
112+
batch instead of retrying it, so compare these limits with your largest requests before you
113+
upgrade, and look for these errors afterwards.
114+
115+
To migrate, do one of these:
116+
117+
- Configure each shipper to send at most 10,000 events per request (Kinesis records, or
118+
OTEL log records with JSON object bodies), and to send each record as an event of its own
119+
(an element of a top-level array, or a Kinesis record of its own) instead of wrapping
120+
many of them in the array of one event.
121+
- Raise the limits to fit your largest requests. `P_MAX_FLATTEN_ROWS_PER_REQUEST` must be at
122+
least the number of events in a request, plus the rows their arrays add.
123+
`P_MAX_FLATTEN_ROWS_PER_EVENT` must be at least the length of the longest array of one
124+
event (the product of the lengths, for sibling arrays). The request size limit and the
125+
byte limit are independent. Raising `P_MAX_EVENT_PAYLOAD_SIZE`, which can go up to
126+
100 MiB, lets larger requests in, but the rows they expand into are still held to
127+
`P_MAX_FLATTEN_BYTES_PER_REQUEST` (64 MiB by default) and to the row limits, so raise
128+
those too for larger flat batches. Higher limits let a request use more memory.
129+
130+
## Internal dataset statistics (`pstats`)
131+
132+
Parseable computes statistics for every parquet file it uploads (unless
133+
`P_COLLECT_DATASET_STATS` is off) and ingests them into the internal `pstats` dataset, one
134+
row for every distinct value of every field (up to `P_MAX_FIELD_STATISTICS` per field), and
135+
one row for a field without distinct values. These rows are not generically flattened.
136+
They are built straight from the statistics, with the fields and values that flattening
137+
gave them before, one row at a time, and each row is ingested before the next is built. So
138+
the row limits do not apply, and the statistics of a file are ingested in full however many
139+
rows they take.
65140

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`.
141+
The byte limit applies to each row on its own. A row is measured before it is built. A row
142+
larger than `P_MAX_FLATTEN_BYTES_PER_REQUEST` as compact JSON, which takes a distinct value
143+
or a field name of about that size, is skipped with a warning that names the stream, the
144+
file and the field (cut to 128 characters), but no value. The other rows of the file are
145+
still ingested. A failure to compute or ingest the statistics of a file is logged as a
146+
warning, with the stream, the tenant and the file.
68147

69148
## When a request is rejected
70149

71150
The error message names the limit that was exceeded and its value. To get under the limit,
72151
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.
152+
smaller requests. You can also raise the limit, see
153+
[Upgrading](#upgrading-requests-that-are-now-rejected).
74154

75-
`tools/flatten-bench/http_smoke.py` checks these responses against a built server binary.
155+
`tools/flatten-bench/http_smoke.py` checks these responses against a built server binary,
156+
including flat batches at and just over the rows per request.

‎src/cli.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -659,7 +659,7 @@ pub struct Options {
659659
env = "P_MAX_FLATTEN_ROWS_PER_REQUEST",
660660
default_value_t = DEFAULT_MAX_FLATTEN_ROWS_PER_REQUEST,
661661
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"
662+
help = "Maximum number of rows all events of an ingest request may expand into when their nested arrays are flattened. Every event takes at least one row, including an event without arrays"
663663
)]
664664
pub max_flatten_rows_per_request: usize,
665665

‎src/handlers/http/kinesis.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ struct Data {
5353
// The data field is base64 encoded JSON (there can be multiple data fields), and there is a requestId and timestamp field.
5454
// Each decoded data field is one event for `budget`, even when it holds an array, charged
5555
// for its generic rows or, when larger, those rows structurally flattened, plus the metadata.
56+
// It is charged before its rows are built; when that fails, the rows built for the records
57+
// before it are dropped with the error.
5658
// Kinesis logs are flattened to the following format:
5759
// {
5860
// "CHANGE": 3.16,

‎src/handlers/http/modal/utils/ingest_utils.rs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -446,7 +446,9 @@ pub fn push_logs(
446446

447447
/// Zero-allocation JSON byte size counter.
448448
/// Uses serde_json::to_writer with a writer that only counts bytes.
449-
pub fn json_byte_size(value: &Value) -> u64 {
449+
/// Exact for values that always serialize, such as a `Value` or a struct of strings and
450+
/// numbers, which is what it is used for.
451+
pub fn json_byte_size(value: &(impl serde::Serialize + ?Sized)) -> u64 {
450452
struct CountingWriter(u64);
451453
impl std::io::Write for CountingWriter {
452454
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
@@ -458,7 +460,7 @@ pub fn json_byte_size(value: &Value) -> u64 {
458460
}
459461
}
460462
let mut counter = CountingWriter(0);
461-
// serde_json::to_writer won't fail on Value types
463+
// serde_json::to_writer won't fail on those
462464
let _ = serde_json::to_writer(&mut counter, value);
463465
counter.0
464466
}

‎src/otel/logs.rs‎

Lines changed: 35 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -413,8 +413,9 @@ pub fn flatten_otel_protobuf(
413413

414414
/// this function performs the custom flattening of the otel logs
415415
/// and returns a `Vec` of `Value::Object` of the flattened json
416-
/// Fails, with nothing returned, once a log body is over the limits of `budget`, which is
417-
/// shared by all records of the request
416+
/// Every record is charged to `budget`, which all records of the request share, before the
417+
/// rows of its bodies are built. Fails once a record would go over its limits, dropping the
418+
/// records converted before it
418419
pub fn flatten_otel_logs(
419420
message: &LogsData,
420421
tenant_id: &str,
@@ -663,26 +664,36 @@ mod tests {
663664
));
664665
}
665666

667+
// Logs collected for `tenant` over all dates, so that a test running across midnight (UTC)
668+
// still counts what it collected. Each test uses a tenant of its own, as the counter is
669+
// global.
670+
fn logs_collected(tenant: &str) -> u64 {
671+
use prometheus::core::Collector;
672+
673+
crate::metrics::TOTAL_LOGS_COLLECTED_BY_DATE
674+
.collect()
675+
.iter()
676+
.flat_map(|family| family.get_metric())
677+
.filter(|metric| {
678+
metric
679+
.get_label()
680+
.iter()
681+
.any(|label| label.get_name() == "tenant_id" && label.get_value() == tenant)
682+
})
683+
.map(|metric| metric.get_counter().get_value() as u64)
684+
.sum()
685+
}
686+
666687
#[test]
667688
fn logs_collected_metric_counts_only_converted_requests() {
668-
use crate::metrics::TOTAL_LOGS_COLLECTED_BY_DATE;
669-
670-
// A tenant of its own, as the counter is global
671689
let tenant = "flatten-limit-metric-tenant";
672-
let collected = || {
673-
let date = chrono::Utc::now().date_naive().to_string();
674-
TOTAL_LOGS_COLLECTED_BY_DATE
675-
.with_label_values(&["all", &date, tenant])
676-
.get()
677-
};
678-
679-
let before = collected();
690+
let before = logs_collected(tenant);
680691
// Fails on the third record, after the scopes of the first resource were converted
681692
assert!(flatten_otel_logs(&logs(SIX_ROW_BODY), tenant, &mut limits(6, 17)).is_err());
682-
assert_eq!(collected(), before);
693+
assert_eq!(logs_collected(tenant), before);
683694

684695
flatten_otel_logs(&logs(SIX_ROW_BODY), tenant, &mut limits(6, 18)).unwrap();
685-
assert_eq!(collected(), before + 3);
696+
assert_eq!(logs_collected(tenant), before + 3);
686697
}
687698

688699
fn byte_limit(bytes: usize) -> FlattenBudget {
@@ -808,15 +819,7 @@ mod tests {
808819

809820
#[test]
810821
fn logs_collected_metric_is_unchanged_when_a_body_key_is_over_the_budget() {
811-
use crate::metrics::TOTAL_LOGS_COLLECTED_BY_DATE;
812-
813822
let tenant = "flatten-limit-prefix-metric-tenant";
814-
let collected = || {
815-
let date = chrono::Utc::now().date_naive().to_string();
816-
TOTAL_LOGS_COLLECTED_BY_DATE
817-
.with_label_values(&["all", &date, tenant])
818-
.get()
819-
};
820823
let body = wide_body();
821824
let long_key = "k".repeat(128);
822825
let scope = |key: &str| ScopeLogs {
@@ -837,12 +840,19 @@ mod tests {
837840
],
838841
};
839842

840-
let before = collected();
843+
let before = logs_collected(tenant);
841844
assert!(matches!(
842845
flatten_otel_logs(&logs, tenant, &mut byte_limit(4096)),
843846
Err(JsonFlattenError::BytesPerRequestLimitExceeded(4096))
844847
));
845-
assert_eq!(collected(), before);
848+
assert_eq!(logs_collected(tenant), before);
849+
850+
// Without the second resource, the request is converted and counted
851+
let fitting = LogsData {
852+
resource_logs: logs.resource_logs[..1].to_vec(),
853+
};
854+
flatten_otel_logs(&fitting, tenant, &mut byte_limit(4096)).unwrap();
855+
assert_eq!(logs_collected(tenant), before + 1);
846856
}
847857

848858
// Compact JSON bytes of the rows of `body` merged into the record under `key`, once

0 commit comments

Comments
 (0)