Mars Terminal Infrastructure

repository·master·Indexed 12 days ago

https://github.com/tencent/mars

A cross-platform terminal infrastructure component developed by Tencent (used in WeChat) providing core networking, logging, and diagnostic capabilities. The project includes integrations for GoogleTest, GoogleMock, zstd, and micro-ecc, as well as tools for decoding log files.

Tokens
25.9K
Snippets
80
Records
130
Agent score
94%

What's inside Mars

  1. Overview of Zstandard (zstd)

    master

    Zstandard (or zstd) is a fast lossless compression algorithm designed for real-time compression scenarios. It aims to provide compression ratios comparable to or better than zlib while maintaining high speeds. It is implemented as a C library and a command-line utility that supports producing and decoding .zst, .gz, .xz, and .lz4 files.

    Key characteristics:

    • Speed vs. Ratio Trade-off: Users can configure the compression level in small increments to balance speed and ratio.
    • Decompression Performance: Decompression speed remains relatively stable across different compression settings.
    • Small Data Optimization: Supports a 'training mode' to create dictionaries for highly efficient compression of small data sets.
  2. Overview of Mars components

    master

    Mars is a cross-platform terminal infrastructure component used by WeChat. It is composed of several specialized modules:

    • comm: A standalone public library providing core utilities such as socket, thread, message queue, and coroutine.
    • xlog: A high-reliability, high-performance runtime logging component.
    • SDT: A network diagnostic component.
    • STN: The Signaling Transmission Network module, which is the primary part of Mars.
  3. What is Parallel Zstandard (PZstandard)?

    master

    PZstandard is a tool similar to pigz but for the Zstandard format. It enables multi-core compression and decompression by breaking input into equal-sized chunks, compressing each chunk independently into a Zstandard frame, and concatenating them.

    Key features:

    • Zstandard Compatibility: Produces and consumes standard Zstandard format files.
    • Parallel Decompression: Supports parallel decompression for files compressed with PZstandard.
    • Optimized I/O: When decompressing standard Zstandard files, it uses one thread for I/O and another for decompression.
  4. Understand Zstandard Dictionary Format

    master

    Zstandard supports two types of dictionaries:

    1. Raw Content Dictionaries: Free of format restrictions, must be at least 8 bytes. These are treated as the Content part of a formatted dictionary.
    2. Trained Dictionaries (zstd --train): Follow a specific structured format.

    Trained Dictionary Structure

    FieldDescription
    Magic_Number4 bytes, value 0xEC30A437 (little-endian)
    Dictionary_ID4 bytes (little-endian). Use any value except 0. Avoid reserved ranges for public distribution (<= 32767 or >= 2^31).
    Entropy_TablesContains Huffman tables for literals, FSE table for offsets, FSE table for match lengths, and FSE table for literals lengths. Followed by 12 bytes of 3 little-endian offset values.
    ContentThe remaining bytes of the dictionary.

    Note on Content Usage: The Content acts as a 'past' for data compression. Sequence commands can reference offsets into the dictionary. However, once the total output of a decoded frame exceeds the Window_Size, the dictionary is no longer accessible.

  5. Understand the Zstandard Literals Section

    master

    The Literals Section is the first part of a compressed block. It contains the raw data (literals) that will be used during [Sequence Execution]. Literals can be stored in four different ways, determined by the Literals_Block_Type field (the 2 lowest bits of the first byte of the Literals_Section_Header):

    • Raw_Literals_Block (0): Literals are stored uncompressed.
    • RLE_Literals_Block (1): Literals consist of a single byte value repeated Regenerated_Size times.
    • Compressed_Literals_Block (2): Standard Huffman-compressed block, starting with an optional Huffman_Tree_Description.
    • Treeless_Literals_Block (3): Huffman-compressed block that reuses the Huffman tree from the previous Compressed_Literals_Block or a dictionary. If no previous tree is available, this is considered data corruption.

    Literals can be decoded first and then copied, or decoded on-the-fly during sequence execution.

  6. Calculate Window_Size from Window_Descriptor

    master

    The Window_Descriptor (an optional 1-byte field) provides the minimum memory buffer required to decompress a frame. If Single_Segment_flag is set, this descriptor is skipped and Window_Size equals Frame_Content_Size.

    Structure:

    • Bits 7-3: Exponent
    • Bits 2-0: Mantissa

    Calculation Formula:

    windowLog = 10 + Exponent;
    windowBase = 1 << windowLog;
    windowAdd = (windowBase / 8) * Mantissa;
    Window_Size = windowBase + windowAdd;

    Constraints:

    • Minimum Window_Size: 1 KB.
    • Maximum Window_Size: (1<<41) + 7*(1<<38) bytes (~3.75 TB).
    • Recommendation: Decoders should support up to 8 MB for interoperability. Encoders should avoid generating frames requiring more than 8 MB unless necessary.
  7. Understand FSE (Finite State Entropy) encoding

    master

    FSE is an entropy codec based on Asymmetric Numeral Systems (ANS) used for compressing symbols like Literals_Length_Code, Match_Length_Code, and offset codes.

    Key Characteristics:

    • Directionality: FSE bitstreams are read from end to beginning. While the bit order within a byte is not reversed, the elements themselves are processed in reverse order of how they were written.
    • State Management: Decoding involves a state carried between symbols. An initial state is obtained by consuming Accuracy_Log bits as a little-endian value.
    • Decoding Table: The table size is a power of 2. Each entry contains a Symbol, Num_Bits, and Baseline. To get the next state, the decoder consumes Num_Bits from the stream and adds it to the Baseline.
  8. How Repeat Offsets work in Zstandard

    master

    Zstandard uses special offset values (1, 2, and 3) to refer to recently used offsets, known as Repeated_Offset values. These are sorted by recency:

    • Repeated_Offset1: Most recent offset.
    • Repeated_Offset2: Second most recent.
    • Repeated_Offset3: Third most recent.

    Standard Usage

    If offset_value is 1, 2, or 3, the decoder uses the corresponding Repeated_Offset.

    Exception: Zero Literal Length

    If the current sequence has literals_length == 0, the repeated offsets are shifted:

    • offset_value == 1 $\rightarrow$ Repeated_Offset2
    • offset_value == 2 $\rightarrow$ Repeated_Offset3
    • offset_value == 3 $\rightarrow$ Repeated_Offset1 - 1_byte

    Offset History Updates

    When a new offset is added to the history:

    • Common Case (New offset not in history):
      • Repeated_Offset3 = Repeated_Offset2
      • Repeated_Offset2 = Repeated_Offset1
      • Repeated_Offset1 = NewOffset
    • If NewOffset == Repeated_Offset2: Repeated_Offset1 and Repeated_Offset2 ranks are swapped; Repeated_Offset3 is unchanged.
    • If NewOffset == Repeated_Offset1: History remains unmodified.
  9. Convert weights to Huffman prefix codes

    master

    To transform decoded weights into Huffman prefix codes, follow these steps:

    1. Calculate Bits: For each symbol, calculate Number_of_Bits = (Weight > 0) ? Max_Number_of_Bits + 1 - Weight : 0.
    2. Sort: Sort symbols by Weight. For symbols with the same weight, maintain their natural sequential order.
    3. Filter: Remove symbols with a weight of zero.
    4. Distribute: Starting from the lowest weight, distribute prefix codes in sequential order.

    Example Weight Distribution:

    Literal012345
    Weight432011

    Resulting Codes:

    Literal345210
    Weight011234
    Number_of_Bits044321
    prefix codesN/A00000001001011
  10. Understand Huffman Tree header encoding

    master

    The Huffman Tree header is a single byte (0-255) that determines how the series of weights is encoded. The encoding method depends on the value of the headerByte:

    • FSE Compression (headerByte < 128): The weights are compressed using Finite State Entropy (FSE). The length of the FSE-compressed series is equal to the value of headerByte (0-127).
    • Direct Representation (headerByte >= 128): Weights are encoded directly as 4-bit fields (0-15).
      • Weights are encoded forward, with two weights per byte (the first weight takes the top 4 bits, the second takes the bottom 4 bits).
      • The number of weights is calculated as Number_of_Weights = headerByte - 127.
      • This method supports up to 128 weights (alphabet sizes up to 129 symbols). If any literal symbol > 128 has a non-zero weight, you must use FSE instead.
  11. Decode Finite State Entropy (FSE) Huffman weights

    master

    When the Huffman Tree header indicates FSE compression, the weights are stored as a single bitstream with two interleaved states (State1 and State2) that share a single distribution table.

    Key decoding details:

    • Compressed Size: Provided by the headerByte.
    • Max Decompressed Size: Always 255 (since literal values span 0-255).
    • Interleaving: State1 encodes even-indexed symbols, and State2 encodes odd-indexed symbols. They take turns decoding a single symbol and updating their state.
    • Termination: Decoding stops when the bitstream reaches an overflow condition (where updating the state would require more bits than remain in the stream), at which point remaining bits are assumed to be 0.
  12. Use Long Distance Matching mode

    master

    The --long mode is designed to improve compression ratios for files with long matches at large distances (up to 128 MiB).

    Trade-offs:

    • Memory: Increases memory usage for both compressor and decompressor.
    • Compression Speed: May degrade if few long matches are found.
    • Decompression Speed: Usually improves when many long distance matches are present.

    This mode is highly effective for files like multiple versions of the same dataset (e.g., different versions of a source code repository).

    zstd --long -1 file.dat