Skip to content

perf(khifile): optimize in-memory model via flat structure-of-arrays representation - #950

Merged
kyasbal merged 6 commits into
GoogleCloudPlatform:mainfrom
kyasbal:push-zsrkquunrnyt
Sep 3, 2026
Merged

kyasbal merged 6 commits into
GoogleCloudPlatform:mainfrom
kyasbal:push-zsrkquunrnyt

Conversation

@kyasbal

@kyasbal kyasbal commented Sep 3, 2026

Copy link
Copy Markdown
Member

Overview

Analysis of heap profiles during the log inspection (collection & generation) phase showed that ~88% of live heap allocations were concentrated in ToInternedStruct (individual *pb.InternedValue allocations) and LogAccumulator (pointer graph of staged logs).

This PR transitions the in-memory staging models to flat, pointer-free Structure-of-Arrays (SoA) representations while preserving on-disk .khi format and streaming chunk compatibility.


Key Changes

1. Direct Node Encoding into FlatStructStore

  • Added StoreFromNodes to FlatStructStore, encoding structured.Node scalars and sequences directly into contiguous primitive value slices (kinds, scalarInts, scalarFloats, scalarStrings, listOffsets).
  • Implemented ensureNestedMapsInterned to pre-intern nested maps into InternPool before acquiring store lock, preventing lock contention and deadlocks.

2. Integrate FlatStructStore into InternPool and ToInternedStruct

  • Replaced idToStruct []*pb.InternedStruct and unflushedStructs []*pb.InternedStruct in InternPool with flatStructs *FlatStructStore and unflushedStructIDs []uint32.
  • ToInternedStruct now directly calls StoreFromNodes on cache miss, eliminating temporary *pb.InternedValue allocations.
  • Removed obsolete legacy conversion helpers (ToInternedValue, scalarToInternedValue, etc.) adhering to the zero-backward-compatibility policy.
  • Transient *pb.InternedStruct messages are only constructed during chunk protobuf serialization and compressed immediately.

3. Store Staged Logs in Flat Primitive Slices in LogAccumulator

  • Replaced currentBatch []*pb.Log in LogAccumulator with flat SoA slices (batchIDs, batchTimestamps, batchLogTypeIDs, batchSeverityIDs, batchSummaryIDs, batchBodyStructIDs).
  • AddLog converts metadata and appends scalar values directly into primitive arrays without allocating heap *pb.Log or *timestamppb.Timestamp objects.
  • flushLocked stably sorts permutation indices based on timestamps, writes the chunk, and resets slice lengths ([:0]) to reuse allocated backing capacity across batches.

E2E Benchmark: Memory Consumption Results

Measured via /usr/bin/time -v and Go pprof memory profiles (--memprofile) on a 4-hour production cluster log query (p0-gke-basic-1, 10 features, 42,478+ logs):

Metric Baseline Optimized Delta % Change
Max Resident Set Size (Peak RSS) 2,512,676 KB (~2.40 GB) 1,933,472 KB (~1.84 GB) -579,204 KB (-565.6 MB) -23.0%
Minor Page Faults 321,992 58,013 -263,979 -82.0%
Live Heap In-Use Space 737.09 MB 409.33 MB -327.76 MB -44.5%
Live Heap In-Use Objects 16,802,357 objects 9,064,750 objects -7,737,607 objects -46.1%
Output .khi Size 20.46 MB 20.42 MB -0.04 MB (identical)

Top Allocations Breakdown (pprof diff)

  • scalarToInternedValue: -320.52 MB (-5,988,669 objects) (100% eliminated from live heap)
  • ToInternedValue: -384.02 MB cum (-7,658,528 objects cum) (100% eliminated)
  • LogAccumulator.AddLog: -315.67 MB cum (-7,431,052 objects cum) (-48.4% live memory)
  • FlatStructStore: Only +104.61 MB of primitive array capacity was needed to hold all structured data, yielding a net reduction of ~545 MB in struct storage.

Verification

  • make pre-commit: PASS
  • make lint-go && make lint-web: PASS (0 issues)
  • make test-go && make test-web: PASS (all Go tests and 1088 web tests pass)
  • E2E inspection job completed with exit code 0 and verified output file integrity.
Refactor InternPool and LogAccumulator to flush compressed chunks directly to the destination Writer as items are added and the batch size threshold is reached, instead of retaining all logs and intern items in memory until the end of the inspection.

- Pass *Writer to InternPool and LogAccumulator and enable progressive chunk compression and writing.
- Remove full in-memory log list and GetLog from LogAccumulator to drastically reduce memory usage during inspection.
- Add thread-safe Mutex to Writer and introduce MustNewTestWriter for testing.
- Update Builder lifecycle and inspection runner to initialize Writer at the start of inspection.
- Update TimelineChangeSet.Flush to accept LogAccumulator directly.
- Add streaming flush unit tests for InternPool and LogAccumulator.
- Relax strict non-decreasing timestamp check in web LogStore to support multi-chunk streaming loads.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors the KHI v6 file generation to stream chunks directly to a destination writer during ingestion, optimizing memory usage and heap allocations through a new FlatStructStore and streaming flushes in InternPool and LogAccumulator. Additionally, the frontend LogStore was updated to accept out-of-order timestamps since the backend now handles chronological sorting during flushes. The reviewer feedback suggests robust error handling for background streaming flushes by adding an error field to InternPool and using a deferred function in Builder.Build to guarantee the writer is closed, preventing potential resource leaks.

Comment thread pkg/model/khifile/v6/intern.go Resolved
Comment thread pkg/model/khifile/v6/intern.go Resolved
Comment thread pkg/model/khifile/v6/builder.go Resolved
Comment thread pkg/model/khifile/v6/builder.go Resolved
@kyasbal

kyasbal commented Sep 3, 2026

Copy link
Copy Markdown
Member Author

E2E Performance Benchmark Update (Post-Review Feedback)

Following the review feedback to store unflushed strings and field path sets as compact Go value types (stagedString and stagedFieldSet) directly in slices instead of heavyweight *pbv6 protobuf pointers:

Metric Baseline Round 1 (SoA PR #950) Round 2 (Value Types) Total Improvement vs Baseline Improvement vs Round 1
Peak RSS 2,512,676 KB (2.40 GB) 1,933,472 KB (1.84 GB) 1,806,940 KB (1.72 GB) -705,736 KB (-28.1%) -126,532 KB (-6.5%)
In-Use Objects 16,802,357 objects 9,064,750 objects 3,951,355 objects -12,851,002 (-76.5%) -5,113,395 (-56.4%)
In-Use Heap Space 737.09 MB 409.33 MB 410.94 MB -326.15 MB (-44.2%) ~flat
scalarToInternedValue 320.52 MB (5,988,669 obj) 0 MB (0 obj) 0 MB (0 obj) -100% (eliminated) -
Staged Protobuf Pointers Millions ~5,000,000 0 (value slices reused) -100% -100%

Key Highlights

  • Live heap objects plummeted from 9.06M to 3.95M (-56.4%): Staging strings and field path sets as flat value slices eliminated over 5.1 million intermediate protobuf message and pointer allocations on every intern call.
  • Peak RSS dropped another ~123.6 MB: Total peak RSS reduction reached -689.2 MB (-28.1%) compared to baseline.
@kyasbal
kyasbal marked this pull request as ready for review September 3, 2026 06:23
@kyasbal
kyasbal merged commit 1807204 into GoogleCloudPlatform:main Sep 3, 2026
17 checks passed
@kyasbal
kyasbal deleted the push-zsrkquunrnyt branch September 3, 2026 06:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

1 participant