semcode

Semcode Database Schema

This document describes the LanceDB database schema used by semcode for storing and querying C/C++ code analysis results.

Overview

Semcode uses LanceDB (Apache Arrow-based columnar database) with several key architectural features:

Database Technology

Database Tables

The database consists of the following tables:

  1. functions - Function definitions, declarations, and function-like macros with embedded call and type relationships
  2. types - Struct, union, and enum definitions with embedded type dependencies
  3. vectors - CodeBERT embeddings for semantic search of functions and types
  4. commit_vectors - Embeddings for git commit messages and diffs
  5. processed_files - Tracks processed files for incremental indexing
  6. symbol_filename - Fast lookup cache mapping symbols to file paths
  7. git_commits - Git commit metadata with unified diffs and changed symbols
  8. lore - Lore.kernel.org email archive with FTS indices for fast searching
  9. lore_vectors - Vector embeddings for semantic search of lore emails
  10. indexed_branches - Tracks which git branches have been indexed with their tip commits
  11. content_0 through content_15 - Deduplicated content storage (16 shards)
  12. dispatch_sites - Calls that go through a value rather than naming a function
  13. data_accesses - Data accesses on structs with how each is touched
  14. registrations - Functions installed in a struct member
  15. unresolved_edges - Edges that cannot be recorded, and where to look
  16. file_includes - Per-file #include / #include_next directives extracted from C/C++ files
  17. base_classes - Each class’s direct bases, as written
  18. schema_meta - What wrote the index

Table Schemas

1. functions

Stores analyzed C/C++ function definitions, declarations, and function-like macros with content deduplication.

Note: Function-like macros are stored in this table with empty return_type and untyped parameters (empty type_name in ParameterInfo).

Schema:

name                (Utf8, NOT NULL)     - Function name
file_path           (Utf8, NOT NULL)     - Source file path
git_file_hash       (Utf8, NOT NULL)     - SHA-1 hash of file content as hex string
line_start          (Int64, NOT NULL)    - Starting line number
line_end            (Int64, NOT NULL)    - Ending line number
return_type         (Utf8, NOT NULL)     - Function return type
parameters          (Utf8, NOT NULL)     - JSON-encoded parameter list
body_hash           (Utf8, nullable)     - Blake3 hash referencing content table as hex string (nullable for empty bodies)
calls               (Utf8, nullable)     - JSON array mixing plain callee spellings and tagged edges carrying the enclosing scope
                                   (`"get"`, `{"call":"get","owner":"ns::Box"}`)
types               (Utf8, nullable)     - JSON array of type names used by this function
guard               (Utf8, NOT NULL)     - Preprocessor arm holding the definition, "" at file scope
qualifier           (Utf8, NOT NULL)     - Owning entity (`module::Type` for a Rust method), "" where the name stands alone
is_static           (Boolean, NOT NULL)  - True for C/C++ internal-linkage functions (file-scope `static` or C++ anonymous namespace; note: preprocessor-hidden `STATIC` macros are not expanded)
is_virtual          (Boolean, nullable)  - Set where a C++ declaration spells the method virtual
method_qualifiers   (Utf8, nullable)     - The method's trailing cv and ref qualifiers (`const`, `volatile`, `&`, `&&`), canonicalised; `""` where a C++ method spells none, null where the row is not a C++ method or predates the column

The functions merge key is (name, file_path, git_file_hash, guard, qualifier, line_start). Two definitions at different lines never merge; a declaration folds into its same-key definition. Overloads sharing one line collapse to one row: the line is the only discriminator the key keeps until a signature column separates them.

Content Storage:

Rust Struct: FunctionInfo

Indices:

2. types

Stores struct, union, enum, and typedef definitions with content deduplication and embedded type dependency data.

Schema:

name                (Utf8, NOT NULL)     - Type name
file_path           (Utf8, NOT NULL)     - Source file path
git_file_hash       (Utf8, NOT NULL)     - SHA-1 hash of file content as hex string
line                (Int64, NOT NULL)    - Line number where type is defined
kind                (Utf8, NOT NULL)     - Type kind: "struct", "union", "enum", "typedef"
size                (Int64, nullable)    - Size in bytes (if available)
fields              (Utf8, NOT NULL)     - JSON string of field/member information
definition_hash     (Utf8, nullable)     - Blake3 hash referencing content table as hex string (nullable for empty definitions)
types               (Utf8, nullable)     - JSON array of type names referenced by this type
qualifier           (Utf8, NOT NULL)     - Owning entity (`ns` for `ns::Box`), "" where nothing owns the type

The types merge key is (name, kind, file_path, git_file_hash, qualifier). A method’s functions.qualifier joins as types.qualifier plus the separator plus types.name (:: for Rust/C++, . for Python/Zig).

Content Storage:

Example JSON columns:

// fields column (for struct/union)
[
  {"name": "id", "type_name": "int", "offset": null},
  {"name": "name", "type_name": "char *", "offset": null},
  {"name": "next", "type_name": "struct node *", "offset": null}
]

// types column
["struct node", "size_t"]

Indices:

3. vectors

Stores CodeBERT embeddings for semantic search functionality.

Schema:

content_hash        (Utf8, NOT NULL)                         - Blake3 hash of content as hex string
vector              (FixedSizeList[Float32, 256], NOT NULL)  - CodeBERT embedding vector

Notes:

Indices:

4. processed_files

Tracks which files have been processed for incremental indexing.

Schema:

file                (Utf8, NOT NULL)     - File path
git_sha             (Utf8, nullable)     - Git commit SHA as hex string (for incremental processing)
git_file_sha        (Utf8, NOT NULL)     - SHA-1 hash of specific file content as hex string
extractor_version   (Utf8, nullable)     - Version of the language that read the file

Notes:

Indices:

5. symbol_filename

Fast lookup cache mapping symbol names to file paths. Optimizes git-aware queries by avoiding full table scans.

Schema:

symbol              (Utf8, NOT NULL)     - Symbol name (function, type, or typedef)
filename            (Utf8, NOT NULL)     - File path where symbol is defined

Purpose:

Performance Benefits:

Indices:

6. commit_vectors

Stores embeddings for git commit messages and diffs, enabling semantic search across commits.

Schema:

git_commit_sha      (Utf8, NOT NULL)                         - Git commit SHA
vector              (FixedSizeList[Float32, 256], NOT NULL)  - Embedding vector for commit

Notes:

Indices:

7. git_commits

Stores git commit metadata including unified diffs and symbols changed in each commit. Enables commit-level analysis and tracking code evolution across git history.

Schema:

git_sha             (Utf8, NOT NULL)     - Git commit SHA
parent_sha          (Utf8, NOT NULL)     - Parent commit SHAs (JSON array)
author              (Utf8, NOT NULL)     - Author name and email
subject             (Utf8, NOT NULL)     - Single line commit title
message             (Utf8, NOT NULL)     - Full commit message
tags                (Utf8, NOT NULL)     - JSON object of tags (Signed-off-by, Reviewed-by, etc.)
diff                (Utf8, NOT NULL)     - Full unified diff with enhanced hunk headers
symbols             (Utf8, NOT NULL)     - JSON array of changed symbols (functions, types, macros)
files               (Utf8, NOT NULL)     - JSON array of changed file paths

Symbol Extraction:

Tag Parsing: Structured metadata extracted from commit messages including:

Example JSON columns:

// parent_sha column (single parent)
["abc123def456..."]

// parent_sha column (merge commit with multiple parents)
["abc123def456...", "789012fed321..."]

// symbols column
["mm_fault_error()", "struct vm_area_struct", "handle_mm_fault()"]

// files column
["mm/memory.c", "include/linux/mm.h"]

// tags column
{
  "Signed-off-by": ["John Doe <john@example.com>"],
  "Reviewed-by": ["Jane Smith <jane@example.com>"],
  "Fixes": ["a1b2c3d4 (\"Fix memory leak in handler\")"]
}

Indices:

Use Cases:


8. lore

Stores lore.kernel.org email archives for searching kernel development discussions, patches, and reviews.

Schema:

git_commit_sha      (Utf8, NOT NULL)     - Git commit SHA from lore repository
from                (Utf8, NOT NULL)     - Sender email address
date                (Utf8, NOT NULL)     - ISO 8601 timestamp
message_id          (Utf8, NOT NULL)     - Unique Message-ID (primary key)
in_reply_to         (Utf8, nullable)     - Message-ID of parent email
subject             (Utf8, NOT NULL)     - Email subject line
references          (Utf8, nullable)     - Space-separated Message-IDs of thread ancestors
recipients          (Utf8, NOT NULL)     - Comma-separated To/Cc recipients
body                (Utf8, NOT NULL)     - Email body content
symbols             (Utf8, NOT NULL)     - JSON array of symbols found in patches/diffs

Indices:

Search Performance: All lore searches use a two-phase FTS + regex post-filtering approach:

  1. FTS phase: Fast keyword extraction and inverted index lookup returns superset
  2. Regex phase: Precise pattern matching on small FTS result set in memory

This provides both speed (FTS indices) and precision (full regex support).

Threading Support: Emails are linked via in_reply_to and references fields for thread reconstruction.


9. lore_vectors

Stores 256-dimensional vector embeddings for semantic search of lore emails.

Schema:

message_id          (Utf8, NOT NULL)     - Email Message-ID (links to lore table)
vector              (FixedSizeList[Float32, 256], NOT NULL) - Semantic embedding

Vector Generation: Embeddings combine from, subject, recipients, and body into a single representation for similarity search.

Index:

10. indexed_branches

Tracks which git branches have been indexed, enabling multi-branch support and efficient incremental indexing across branches.

Schema:

branch_name         (Utf8, NOT NULL)     - Branch name (e.g., "main", "origin/develop")
tip_commit          (Utf8, NOT NULL)     - Commit SHA at the tip when indexed (40-char hex)
indexed_at          (Int64, NOT NULL)    - Unix timestamp of when branch was last indexed
remote              (Utf8, nullable)     - Remote name if tracking branch (e.g., "origin")

Purpose:

Use Cases:

Indices:


11. content_0 through content_15 (Content Shards)

Stores deduplicated content referenced by other tables, distributed across 16 shard tables for optimal performance.

Schema (each shard):

blake3_hash         (Utf8, NOT NULL)     - Blake3 hash of content as hex string (primary key)
content             (Utf8, NOT NULL)     - The actual content (function bodies, definitions, expansions)

Content Sharding:

Shard Distribution:

Indices (per shard):

12. dispatch_sites

Calls that dispatch through a value rather than naming a function: ops->read(...), (*fp)(...), a candidate named by an indirect-call macro. A site records what the containing file proves and nothing more; the candidates come from joining it against registrations at query time.

Schema:

caller_name         (Utf8, NOT NULL)     - Function containing the site, empty when there is none
file_path           (Utf8, NOT NULL)     - File containing the site
git_file_hash       (Utf8, NOT NULL)     - Content hash of that file
byte_start          (Int64, NOT NULL)    - Byte offset of the site within the file
line                (Int64, NOT NULL)    - Line of the site
member              (Utf8, NOT NULL)     - Member dispatched through, empty for a plain pointer call
receiver_expr       (Utf8, nullable)     - Receiver as written
receiver_type       (Utf8, nullable)     - Type of the receiver, when the file declares it
receiver_bound      (Utf8, nullable)     - Bound of a receiver typed as a generic
                                           parameter. Set beside the type, or alone
                                           for `impl`/`dyn` parameters
receiver_base_type  (Utf8, nullable)     - For `base->field->m()`, the type of the base
receiver_field      (Utf8, nullable)     - For `base->field->m()`, the field read from it
arity               (Int64, nullable)    - How many arguments the call passes
arg_types           (Utf8, nullable)     - JSON array of the type of each argument, where proven
receiver_form       (Utf8, nullable)     - How the receiver is declared: `object` or `indirect`
kind                (Utf8, NOT NULL)     - member_arrow, member_dot, pointer_param, pointer_local,
                                           pointer_deref, macro_declared
target              (Utf8, NOT NULL)     - A target the site names itself, empty otherwise

Notes:

Indices:

13. data_accesses

Every recorded access of named data: s->tag, with how it is touched (read, written, address-taken) and what the containing file proves about the receiver. Owning structs are not stored: a name alone does not name its struct, so resolution joins container_type against the types table at query time, the dispatch-sites pattern.

Coverage: C field_expression nodes with a receiver, outside sizeof.

Schema:

caller_name         (Utf8, NOT NULL)     - Function containing the access, empty when there is none
file_path           (Utf8, NOT NULL)     - File containing the access
git_file_hash       (Utf8, NOT NULL)     - Content hash of that file
byte_start          (Int64, NOT NULL)    - Byte offset of the accessed name within the file
line                (Int64, NOT NULL)    - Line of the access
name                (Utf8, NOT NULL)     - Name of the data accessed
container_type      (Utf8, nullable)     - Type of the receiver, when the file declares it
container_base_type (Utf8, nullable)     - For `base->field->x`, the type of the base
container_field     (Utf8, nullable)     - For `base->field->x`, the field read from it
access              (Utf8, NOT NULL)     - read, write, or addr
receiver_expr       (Utf8, nullable)     - Receiver as written

Notes:

Indices:

14. registrations

Functions installed in a struct member: .read = my_read, or ops->handler = my_handler. The other half of the join.

Schema:

container_type      (Utf8, NOT NULL)     - Struct or union the member belongs to,
                                           or the trait for a trait_impl row
member              (Utf8, NOT NULL)     - Member being installed into
target              (Utf8, NOT NULL)     - What is installed, as written
file_path           (Utf8, NOT NULL)     - File containing the registration
git_file_hash       (Utf8, NOT NULL)     - Content hash of that file
byte_start          (Int64, NOT NULL)    - Byte offset within the file
line                (Int64, NOT NULL)    - Line of the registration
enclosing_function  (Utf8, NOT NULL)     - Function containing it, empty at file scope
kind                (Utf8, NOT NULL)     - designated_init, assignment, or trait_impl

Notes:

Indices:

15. unresolved_edges

Edges the index cannot record, with what it takes to find the other side. callers bdi_debug_stats_show answering “No functions call it” ends a search; naming the mechanism and a place to look lets it continue.

Schema:

name                (Utf8, NOT NULL)     - The end of the edge that is known
direction           (Utf8, NOT NULL)     - in or out, from that end
kind                (Utf8, NOT NULL)     - Mechanism, namespaced by language:
                                           c:macro_parameter_call,
                                           rust:unrecognized_call_shape, and
                                           others as they are recorded
evidence            (Utf8, NOT NULL)     - What the source writes where the name
                                           would be: a macro parameter, a pasted
                                           fragment, an attribute string
locations           (Utf8, NOT NULL)     - JSON [{role, file_path, line}]; role is
                                           definition, invocation, declaration,
                                           installation or stub
file_path           (Utf8, NOT NULL)     - The first location, for indexing
git_file_hash       (Utf8, NOT NULL)     - Content hash of that file
line                (Int64, NOT NULL)    - Line of the first location

Notes:

Indices:

16. file_includes

Per-file #include and #include_next directives extracted by Tree-sitter from C and C++ source and header files, used for translation-unit callee resolution.

Schema:

file_path           (Utf8, NOT NULL)     - Including file path (repo-relative)
git_file_hash       (Utf8, NOT NULL)     - SHA-1 hash of file content as hex string
line                (UInt32, NOT NULL)   - 1-based line number of the directive in `file_path`
target              (Utf8, NOT NULL)     - Included path inside "..." or <...>, or raw expression when `is_computed` is true
is_system           (Boolean, NOT NULL)  - True for <...>, false for "..." or computed includes
is_next             (Boolean, NOT NULL)  - True for `#include_next`, false for `#include`
is_computed         (Boolean, NOT NULL)  - True for computed `#include MACRO(...)` directives
is_guarded          (Boolean, NOT NULL)  - True when inside a `#if`/`#ifdef`/`#ifndef` guard (excluding header include guards)

The file_includes merge key is (file_path, git_file_hash, line, target, is_system, is_next, is_computed, is_guarded).

Indices:

17. base_classes

Each class’s direct bases, as the file spells them: one row per class Child : ... Base edge. The transitive closure is walked at query time against the functions table’s virtual flags, so this holds only what each file proves about its own classes.

Schema:

child               (Utf8, NOT NULL)     - The class naming the base, qualified
base                (Utf8, NOT NULL)     - The base as written in the base clause
file_path           (Utf8, NOT NULL)     - File containing the class
git_file_hash       (Utf8, NOT NULL)     - Content hash of that file

Notes:

Indices:

18. schema_meta

What wrote the index.

Schema:

key                 (Utf8, NOT NULL)     - schema_version, created
value               (Utf8, NOT NULL)     - The value

Notes:

Key Features

Content Deduplication Architecture

Blake3-based Content Storage:

Content Resolution:

// Function body content is resolved via appropriate content shard lookup
let shard_table = format!("content_{}", get_shard_number(&function.body_hash));
let body_content = content_store.get_content(&function.body_hash).await?;

Content Sharding System

16-Way Sharding:

Sharding Benefits:

Embedded JSON Relationships

Function calls example (optimized with BTree index on calls):

-- Find all functions that call 'malloc'
SELECT name, file_path FROM functions
WHERE calls IS NOT NULL AND calls LIKE '%"malloc"%'

Type dependencies example (optimized with BTree index on types):

-- Find all functions that use 'struct node'
SELECT name, file_path FROM functions
WHERE types IS NOT NULL AND types LIKE '%"struct node"%'

-- Find all types that reference 'struct node'
SELECT name, kind FROM types
WHERE types IS NOT NULL AND types LIKE '%"struct node"%'

Performance benefits:

Git SHA-based Content Tracking

Every record includes a git_file_hash field containing the SHA-1 hash of the file content as a hex string, enabling:

Symbol Lookup Cache (symbol_filename)

The symbol_filename table acts as a fast index cache that dramatically improves git-aware query performance:

Problem Solved:

Solution:

Performance Impact:

Usage:

Commit Metadata with Symbol Extraction

The git_commits table stores git commit history with enhanced metadata:

Query Patterns

Basic Lookups

-- Find function by name
SELECT name, file_path, body_hash FROM functions WHERE name = 'main'

-- Find types by kind
SELECT name, definition_hash FROM types WHERE kind = 'struct'

-- Get content from appropriate shard
SELECT content FROM content_5 WHERE blake3_hash = 'abc123...'

Content Resolution Queries

-- Function with body content (join with appropriate content shard)
-- Note: Shard selection done programmatically based on hash
SELECT f.name, f.file_path, c.content as body
FROM functions f
LEFT JOIN content_5 c ON f.body_hash = c.blake3_hash
WHERE f.name = 'main' AND f.body_hash LIKE '5%'

-- Type with definition content
SELECT t.name, t.kind, c.content as definition
FROM types t
LEFT JOIN content_3 c ON t.definition_hash = c.blake3_hash
WHERE t.name = 'user_data' AND t.definition_hash LIKE '3%'

Relationship Queries

-- Find callers of a function (uses BTree index on calls)
SELECT name, file_path FROM functions
WHERE calls IS NOT NULL AND calls LIKE '%"target_function"%'

-- Find functions using a specific type (uses BTree index on types)
SELECT name, file_path FROM functions
WHERE types IS NOT NULL AND types LIKE '%"struct user_data"%'

-- Find all functions that use pointer types
SELECT name, file_path FROM functions
WHERE types IS NOT NULL AND types LIKE '%"*"%'

Line-based and Location Queries

-- Find functions starting after line 100 (uses BTree index on line_start)
SELECT name, file_path, line_start, line_end FROM functions
WHERE line_start > 100 ORDER BY line_start

-- Find functions ending before line 500 (uses BTree index on line_end)
SELECT name, file_path, line_start, line_end FROM functions
WHERE line_end < 500

-- Find large functions (more than 50 lines, uses both line indices)
SELECT name, file_path, (line_end - line_start) as size FROM functions
WHERE (line_end - line_start) > 50 ORDER BY size DESC

-- Find functions in a specific line range
SELECT name, file_path FROM functions
WHERE line_start >= 100 AND line_end <= 200

-- Get functions sorted by location in file (uses BTree index on line_start)
SELECT name, file_path, line_start FROM functions
WHERE file_path = 'src/main.c' ORDER BY line_start

Git-aware Queries

-- Find function at specific git SHA
SELECT * FROM functions
WHERE name = 'parse_config' AND git_file_hash = 'abc123...'

-- Content deduplication analysis across all shards
SELECT blake3_hash, COUNT(*) as usage_count
FROM (
  SELECT body_hash as blake3_hash FROM functions WHERE body_hash IS NOT NULL
  UNION ALL
  SELECT definition_hash FROM types WHERE definition_hash IS NOT NULL
  UNION ALL
  SELECT definition_hash FROM macros WHERE definition_hash IS NOT NULL
) GROUP BY blake3_hash HAVING usage_count > 1

Commit Metadata Queries

-- Find commits by author
SELECT git_sha, subject, author FROM git_commits
WHERE author LIKE '%john@example.com%'

-- Find commits that modified a specific function
SELECT git_sha, subject, author FROM git_commits
WHERE symbols LIKE '%"malloc_wrapper()"%'

-- Find commits that modified any struct definitions
SELECT git_sha, subject, author FROM git_commits
WHERE symbols LIKE '%"struct %'

-- Find commits that modified a specific file
SELECT git_sha, subject, author FROM git_commits
WHERE files LIKE '%"mm/kmemleak.c"%'

-- Find commits that modified files in a directory
SELECT git_sha, subject, author FROM git_commits
WHERE files LIKE '%"mm/%'

-- Get full commit details including diff
SELECT git_sha, subject, message, diff, symbols FROM git_commits
WHERE git_sha = 'abc123...'

-- Find commits with multiple parents (merge commits)
SELECT git_sha, subject, author FROM git_commits
WHERE parent_sha LIKE '%,%'

-- Find commits with specific tags (e.g., reviewed commits)
SELECT git_sha, subject, author FROM git_commits
WHERE tags LIKE '%"Reviewed-by"%'

-- Traverse commit history by following parent relationships
SELECT c1.git_sha, c1.subject, c2.git_sha as parent_sha, c2.subject as parent_subject
FROM git_commits c1, git_commits c2
WHERE c1.parent_sha LIKE '%"' || c2.git_sha || '"%'

Cross-shard Content Analysis

-- Find content usage patterns across shards
-- (This would be done programmatically across all content_N tables)
WITH all_content AS (
  SELECT blake3_hash FROM content_0
  UNION ALL
  SELECT blake3_hash FROM content_1
  -- ... through content_15
)
SELECT COUNT(*) as total_unique_content FROM all_content

Performance Characteristics

Storage Efficiency

Architecture Benefits

Content Deduplication Impact

Content Sharding Benefits

Git Integration Benefits

Hex String Storage Benefits