perfetto icon indicating copy to clipboard operation
perfetto copied to clipboard

Packets dropped with multithreaded TrackEvent, no buffer overwrite

Open kamrann opened this issue 8 months ago • 10 comments

I'm using perfetto for the first time so apologies if I'm just misunderstanding intended usage, but I've been digging into things for two days and can't understand why my traces are getting corrupted. I'm using the C++ SDK and doing nothing other than the default TRACE_EVENT[_BEGIN/END] datasource instrumentation. So far, I haven't seen a problem running single threaded, but when I run tasks in parallel on a large enough workload, I almost always end up with dropped packets which render the result useless.

Here is the relevant data, so far as I understand, from my investigation:

  1. I see various mixtures of the following data loss warnings: traced_buf_trace_writer_packet_loss, traced_buf_sequence_packet_loss and traced_buf_incremental_sequences_dropped. Maybe just one, maybe two or all three. Yet whenever there are any such loss events, the timeline shows up malformed, with some events being marked as incomplete.
  2. Sometimes the timeline length seems as it should be, with the incomplete slices just extending to the end and being far longer than they should be. Other times the incomplete slices just cut short and the trace timeline is much shorter than it should be.
  3. Often I see traced_flushes_succeeded being one less than traced_flushes_requested, but this appears to have no relation to whether or not the results are malformed.
  4. When it is malformed, traced_buf_bytes_read is slightly smaller than traced_buf_bytes_written.
  5. To give an idea of my data volume, the traces I've been doing have been around 2-3 minutes, generating trace files of around half a gigabyte.
  6. Slice nesting depth reaches around 100.
  7. I ran traceconv text as suggested in another issue, and found some packets like the following:
packet {
  previous_packet_dropped: true
  timestamp: 85501
  sequence_flags: 2
  track_event {
    type: TYPE_SLICE_END
  }
  trusted_uid: 0
  trusted_packet_sequence_id: 3
  trusted_pid: 0
}

To give a bit more info on my setup. I trigger a single tracing session, which

  • calls perfetto::Tracing::NewTrace(perfetto::kInProcessBackend)
  • calls Setup() (passing a file) and then StartBlocking
  • the main thread then spawns N workers (std::jthread), all of which along with the main thread run the same code which can emit events
  • the main thread will join with all the worker threads, which are then destroyed
  • only then will the main thread call FlushBlocking (unsure if needed) before StopBlocking and then closing the file

Results are unpredictable, but so far I've seen packet loss for N >= 1, but not for N == 0.

I've experimented with various config values based on suggestions in the docs and elsewhere:

  • I've bumped up the buffer size (add_buffers()->set_size_kb()) to 1GB, which from the stats is more than is being written throughout the whole trace, so there is no overflow happening there.
  • Tried increasing shmem_size_hint_kb and shmem_page_size_hint_kb to various degrees.
  • Experimented with file_write_period and flush_period.
  • Also tried to use BufferExhaustedPolicy::kStall as noted somewhere.

Am I right in thinking that under these conditions, there's really no reason I should be seeing packet loss like this? Any suggestions as to what the cause could be, or ways to debug, would be much appreciated.

Stats from one malformed trace:

clock_sync_cache_miss | 77 | info (analysis)
guess_trace_type_duration_ns | 110163100 | info (analysis)
packet_skipped_seq_needs_incremental_state_invalid | 9715362 | info (analysis)
parse_trace_duration_ns | 7912450300 | info (analysis)
traced_buf_buffer_size[0] | 1073741824 | info (trace)
traced_buf_bytes_read[0] | 363528192 | info (trace)
traced_buf_bytes_written[0] | 363560960 | info (trace)
traced_buf_chunks_read[0] | 11094 | info (trace)
traced_buf_chunks_rewritten[0] | 35 | info (trace)
traced_buf_chunks_written[0] | 11095 | info (trace)
traced_buf_patches_succeeded[0] | 354 | info (trace)
traced_buf_readaheads_failed[0] | 25 | info (trace)
traced_buf_readaheads_succeeded[0] | 234 | info (trace)
traced_buf_sequence_packet_loss[0] | 14 | data_loss (analysis)
traced_chunks_discarded | 19 | info (trace)
traced_data_sources_registered | 1 | info (trace)
traced_data_sources_seen | 20 | info (trace)
traced_flushes_requested | 15 | info (trace)
traced_flushes_succeeded | 15 | info (trace)
traced_producers_connected | 1 | info (trace)
traced_producers_seen | 1 | info (trace)
traced_total_buffers | 1 | info (trace)
traced_tracing_sessions | 1 | info (trace)

kamrann avatar Mar 16 '26 13:03 kamrann

can you share the full trace config used for recording?

The thing that makes more a differnce if whether you are using periodic file writing (write_into_file) or pure ring buffer. If the former, there are some known issues with the V1 TraceBuffer

The first step I'd do is: if you are using write_into_file, what happens if you remove that, and use a pure-ring buffer? do the problems go away? if yes, that rules out 90% of the other potential problems

primiano avatar Mar 16 '26 20:03 primiano

Really appreciate the quick response. And you were right, that seems to have fixed it. The config from my last problematic trace was:

buffers {
  size_kb: 1048576
}
data_sources {
  config {
    name: "track_event"
    buffer_exhausted_policy: BUFFER_EXHAUSTED_STALL_THEN_ABORT
    track_event_config {
      disabled_categories: "*"
      enabled_categories: "kparse.rule"
      enabled_categories: "kdeps"
      enabled_categories: "dl.compilation"
      enabled_categories: "dl.evaluation"
    }
  }
}
write_into_file: true
file_write_period_ms: 25
flush_period_ms: 50

though various values for some of those settings all had the same result. But indeed turning off write_into_file (and using ReadTraceBlocking after StopBlocking) seems to fix it; I've tried 3 multithreaded runs and they all succeeded.

buffers {
  size_kb: 1048576
}
data_sources {
  config {
    name: "track_event"
    track_event_config {
      disabled_categories: "*"
      enabled_categories: "kparse.rule"
      enabled_categories: "kdeps"
      enabled_categories: "dl.compilation"
      enabled_categories: "dl.evaluation"
    }
  }
}
flush_period_ms: 500

So if I handle this manually, is buffer_exhausted_policy still relevant? Is the idea that I just set up a callback or dedicated thread to call ReadTrace frequently enough to avoid the buffer filling up?

If there's anything you'd like me to do to get more info about whatever the problem is with write_into_file please let me know. Otherwise, thanks and feel free to close.

kamrann avatar Mar 17 '26 13:03 kamrann

So if I handle this manually, is buffer_exhausted_policy still relevant?

No I don't that was the problem

Is the idea that I just set up a callback or dedicated thread to call ReadTrace frequently enough to avoid the buffer filling up?

Unfortunately that would create the same problem that write_into_file has. The only solution is wait that we switch to TraceBufferV2, as that will sovle this long-standing issue.

We are in the process of evaluating it (it -> switching to TRACE_BUFFER_V2). right now is behind an experimental flag. Once we hash out all the details it will become the new default.

Unfortunately I don't have a good solution until then

the only other thing you can try is to use perfetto --clone and create snapshots of the ring buffer. However be aware that doing so will give you trace files that can contain duplicate events: i.e. events in the N-th snapshot can contains some late events present also in the N-1 (or even N-2) snapshot. So you can't just "stitch together" the snapshots.

primiano avatar Mar 18 '26 06:03 primiano

Ok understood. Right now I'm just using this for analysing behaviour during development, not production, so I'll look into the experimental flag, or otherwise even if I have to just use a huge buffer with a single readback it's not a major problem. I just need a way to make it reasonably reliable, as the nature of my trace is such that any dropped packet is liable to make it unusable.

Thanks again for your help!

kamrann avatar Mar 18 '26 07:03 kamrann

To update on this issue, we're working through the edge cases around the new TraceBuffer v2 implementation - https://github.com/google/perfetto/pull/5323 was the latest fix which went in today.

There's another edge case which @sashwinbalaji will look into fixing next week. I believe once that lands, we've addressed all the issues we've found so far. We'll stress test internally in Google and then, if everything goes well, we'll make this the default, ideally before Perfetto v55.

LalitMaganti avatar Mar 28 '26 03:03 LalitMaganti

We're continuing to hit further edge cases in V2 but the frequency is reducing and the sort of issues are getitng more and more obscure. I think probably with V57 we will have enough confidence to turn it on by default.

LalitMaganti avatar May 28 '26 23:05 LalitMaganti

similar issue here. trying tbV2 on 58.3 to do trace in a linux app with many threads (250+) on a 4 x86 core system, when doing trace locally with system backend, comparing to V1, I see 'traced_buf_trace_writer_packet_loss' error mitigated (a few times in a 2 minutes session),but if I do it with relay (to collect trace across local muti-machine system), the 'traced_buf_trace_writer_packet_loss' error pumps up to a few houndred, and the message stream is missing many interned-data (including category, name etc.), causing trace processoring issues. The average trace data rate is abort 800KB -1MB per sec, from many threads.

Any fixes, trace configuration tweaks, or app trace inject suggestions here?

aetheln avatar Sep 15 '26 01:09 aetheln

I suspect you're hitting smb (shared memory buffer) exhaustion due to your app having 250+ threads.

Because in the current model once a thread traces even just once, it holds onto a 4KB chunk forever. With enough such threads, other writers can fail to acquire a chunk and drop packets, resulting in traced_buf_trace_writer_packet_loss. This can happen even when the overall trace data rate is relatively low.

We are working on rewriting the tracing service to address this (and many other problems) in https://github.com/google/perfetto/discussions/4508 with some initial PRs already out.

To help confirm this is the case can you share (feel free to redact anything confidential)

  • stats info by running "select * from stats WHERE value != 0" for both local and relay traces.
  • your trace config and sdk init settings.
  • Also do most of those 250+ threads emit occasional events and then remain alive but idle.

Also knowing your config / setting would help to suggest you better tweaks

sashwinbalaji avatar Sep 15 '26 09:09 sashwinbalaji

Few things, I can think of which can help with this:

  • Try frequent incremental_state clearing
  incremental_state_config {
    clear_period_ms: 1000
  }
  • Try adding flushes ideally before the thread becomes idle (https://crsrc.org/c/third_party/perfetto/examples/sdk/example.cc;l=66-67)

  • If you're building the SDK locally you can try to increase the SMB size for relay scenario here (right now it's hardcoded and not configurable) https://crsrc.org/c/third_party/perfetto/src/tracing/core/in_process_shared_memory.h;l=32?q=src%2Ftracing%2Fcore%2Fin_process_shared_memory.h&ss=chromium%2Fchromium%2Fsrc:third_party%2Fperfetto%2F. If this helps let us know and we can try to make it a config option.

sashwinbalaji avatar Sep 15 '26 10:09 sashwinbalaji

some stats (relay mode):

id name key idx severity source value description machine_id trace_id
1 guess_trace_type_duration_ns 71 null info analysis 40300 null null
3 parse_trace_duration_ns 94 null info analysis 1061273900 null null
4 clock_sync_cache_miss 186 null info analysis 609 null null
102 systemd_journal_num_total 120 null info trace 479 0 1
107 traced_chunks_discarded 157 null info trace 9977 0 1
108 traced_data_sources_registered 158 null info trace 48 0 1
109 traced_data_sources_seen 159 null info trace 64 0 1
113 traced_flushes_requested 163 null info trace 64 0 1
114 traced_flushes_succeeded 164 null info trace 64 0 1
116 traced_producers_connected 166 null info trace 10 0 1
117 traced_producers_seen 167 null info trace 10 0 1
118 traced_total_buffers 168 null info trace 3 0 1
119 traced_tracing_sessions 169 null info trace 1 0 1
268 packet_skipped_seq_needs_incremental_state_invalid 345 null notice analysis 237903 A packet with SEQ_NEEDS_INCREMENTAL_STATE flag was skipped because incremental state is invalid. Packets that depend on incremental state cannot be processed until state is reestablished. Root cause: packet loss in the trace (check packet loss stats) or a bug in the trace producer (missing incremental_state_cleared packet). 0 1
269 interned_data_skipped_incremental_state_invalid 346 null notice analysis 130 An InternedData packet was skipped because incremental state is invalid. InternedData must be associated with the correct state generation, so it's ignored until incremental state is cleared. Root cause: packet loss in the trace (check packet loss stats) or a bug in the trace producer (missing incremental_state_cleared packet). 0 1
371 systemd_journal_num_total 120 null info trace 1578 1 1
389 track_event_parser_errors 170 null info analysis 14330 1 1
547 traced_buf_buffer_size 124 0 info trace 50331648 0 1
548 traced_buf_bytes_written 128 0 info trace 98453136 0 1
549 traced_buf_bytes_overwritten 125 0 info trace 40960 0 1
550 traced_buf_bytes_read 126 0 info trace 105509072 0 1
551 traced_buf_padding_bytes_written 138 0 info trace 24369104 0 1
552 traced_buf_padding_bytes_cleared 137 0 info trace 72383264 0 1
553 traced_buf_chunks_written 135 0 info trace 12150 0 1
554 traced_buf_chunks_rewritten 134 0 info trace 2227 0 1
555 traced_buf_chunks_overwritten 131 0 info trace 5 0 1
556 traced_buf_chunks_discarded 130 0 info trace 45 0 1
557 traced_buf_chunks_read 132 0 info trace 13071 0 1
558 traced_buf_chunks_relocated 133 0 info trace 197 TraceBufferV2 only. Num. chunks that we moved to the write cursor instead of rewriting in place. We do this for scraped chunks that have been fully read, as their old position can be too close to the write cursor to be safe. 0 1
559 traced_buf_chunks_committed_out_of_order 136 0 info trace 2 0 1
560 traced_buf_write_wrap_count 154 0 info trace 1 0 1
561 traced_buf_patches_succeeded 140 0 info trace 9337 0 1
563 traced_buf_readaheads_succeeded 142 0 info trace 5205 0 1
564 traced_buf_readaheads_failed 141 0 info trace 16798 0 1
566 traced_buf_trace_writer_packet_loss 143 0 data_loss trace 117 The tracing service observed packet loss for this buffer during this tracing session. This also counts packet loss that happened before the RING_BUFFER start or after the DISCARD buffer end. 0 1
567 traced_buf_buffer_size 124 1 info trace 8388608 0 1
568 traced_buf_bytes_written 128 1 info trace 991712 0 1
570 traced_buf_bytes_read 126 1 info trace 1237472 0 1
573 traced_buf_chunks_written 135 1 info trace 243 0 1
574 traced_buf_chunks_rewritten 134 1 info trace 191 0 1
577 traced_buf_chunks_read 132 1 info trace 303 0 1
578 traced_buf_chunks_relocated 133 1 info trace 2 TraceBufferV2 only. Num. chunks that we moved to the write cursor instead of rewriting in place. We do this for scraped chunks that have been fully read, as their old position can be too close to the write cursor to be safe. 0 1
581 traced_buf_patches_succeeded 140 1 info trace 91 0 1
583 traced_buf_readaheads_succeeded 142 1 info trace 195 0 1
584 traced_buf_readaheads_failed 141 1 info trace 184 0 1
587 traced_buf_buffer_size 124 2 info trace 8388608 0 1
588 traced_buf_bytes_written 128 2 info trace 1352192 0 1
590 traced_buf_bytes_read 126 2 info trace 1352192 0 1
593 traced_buf_chunks_written 135 2 info trace 378 0 1
597 traced_buf_chunks_read 132 2 info trace 378 0 1

local tracing

id name key idx severity source value description machine_id trace_id
1 guess_trace_type_duration_ns 71 null info analysis 48600 null null
3 parse_trace_duration_ns 94 null info analysis 1190178200 null null
4 clock_sync_cache_miss 186 null info analysis 442 null null
102 systemd_journal_num_total 120 null info trace 936 0 1
107 traced_chunks_discarded 157 null info trace 117 0 1
108 traced_data_sources_registered 158 null info trace 25 0 1
109 traced_data_sources_seen 159 null info trace 96 0 1
113 traced_flushes_requested 163 null info trace 52 0 1
114 traced_flushes_succeeded 164 null info trace 52 0 1
116 traced_producers_connected 166 null info trace 6 0 1
117 traced_producers_seen 167 null info trace 6 0 1
118 traced_total_buffers 168 null info trace 3 0 1
119 traced_tracing_sessions 169 null info trace 1 0 1
120 track_event_parser_errors 170 null info analysis 24926 0 1
268 packet_skipped_seq_needs_incremental_state_invalid 345 null notice analysis 147 A packet with SEQ_NEEDS_INCREMENTAL_STATE flag was skipped because incremental state is invalid. Packets that depend on incremental state cannot be processed until state is reestablished. Root cause: packet loss in the trace (check packet loss stats) or a bug in the trace producer (missing incremental_state_cleared packet). 0 1
278 traced_buf_buffer_size 124 0 info trace 50331648 0 1
279 traced_buf_bytes_written 128 0 info trace 91537408 0 1
280 traced_buf_bytes_overwritten 125 0 info trace 24576 0 1
281 traced_buf_bytes_read 126 0 info trace 97099776 0 1
283 traced_buf_padding_bytes_cleared 137 0 info trace 41099264 0 1
284 traced_buf_chunks_written 135 0 info trace 11174 0 1
285 traced_buf_chunks_rewritten 134 0 info trace 1427 0 1
286 traced_buf_chunks_overwritten 131 0 info trace 3 0 1
287 traced_buf_chunks_discarded 130 0 info trace 35 0 1
288 traced_buf_chunks_read 132 0 info trace 11853 0 1
289 traced_buf_chunks_relocated 133 0 info trace 369 TraceBufferV2 only. Num. chunks that we moved to the write cursor instead of rewriting in place. We do this for scraped chunks that have been fully read, as their old position can be too close to the write cursor to be safe. 0 1
291 traced_buf_write_wrap_count 154 0 info trace 1 0 1
292 traced_buf_patches_succeeded 140 0 info trace 8268 0 1
294 traced_buf_readaheads_succeeded 142 0 info trace 4674 0 1
295 traced_buf_readaheads_failed 141 0 info trace 8785 0 1
298 traced_buf_buffer_size 124 1 info trace 8388608 0 1
299 traced_buf_bytes_written 128 1 info trace 753664 0 1
301 traced_buf_bytes_read 126 1 info trace 950272 0 1
304 traced_buf_chunks_written 135 1 info trace 184 0 1
305 traced_buf_chunks_rewritten 134 1 info trace 49 0 1
308 traced_buf_chunks_read 132 1 info trace 232 0 1
309 traced_buf_chunks_relocated 133 1 info trace 51 TraceBufferV2 only. Num. chunks that we moved to the write cursor instead of rewriting in place. We do this for scraped chunks that have been fully read, as their old position can be too close to the write cursor to be safe. 0 1
312 traced_buf_patches_succeeded 140 1 info trace 49 0 1
314 traced_buf_readaheads_succeeded 142 1 info trace 98 0 1
318 traced_buf_buffer_size 124 2 info trace 8388608 0 1
319 traced_buf_bytes_written 128 2 info trace 647216 0 1
321 traced_buf_bytes_read 126 2 info trace 647216 0 1
324 traced_buf_chunks_written 135 2 info trace 137 0 1
328 traced_buf_chunks_read 132 2 info trace 137 0 1
338 traced_buf_sequence_packet_loss 144 0 data_loss analysis 3 The number of groups of consecutive packets lost in each sequence for this buffer 0 1
345 traced_buf_data_loss_overwrite 151 0 data_loss trace 3 Sequence data losses TraceBufferV2 attributed to a ring-buffer wrap evicting unread chunks, per buffer. 0 1

aetheln avatar Sep 15 '26 10:09 aetheln