Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

fix(kb): boundary-aware chunking with overlap for KB ingest (#277) (#321)

Aadit Singal81dc448a86ff
diff --git a/services/api/app/api/v1/endpoints/knowledge_base.py b/services/api/app/api/v1/endpoints/knowledge_base.py
index 2f06faa44..1f1db2f62 100644
--- a/services/api/app/api/v1/endpoints/knowledge_base.py
+++ b/services/api/app/api/v1/endpoints/knowledge_base.py
@@ -28,6 +28,7 @@ from sqlalchemy import text
from app.api.v1.deps import AuthUser, DBSession
from app.core.airgap import AirgapViolation, enforce_airgap_for_url
+from app.services.kb_chunking import chunk_text
logger = logging.getLogger(__name__)
@@ -38,7 +39,6 @@ router = APIRouter(prefix="/kb", tags=["knowledge_base"])
# ────────────────────────────────────────────────────────────────────────────
DocKind = Literal["runbook", "policy", "playbook", "sop", "wiki", "other"]
-_CHUNK_SIZE = 800 # characters per chunk
class IngestRequest(BaseModel):
@@ -89,10 +89,6 @@ class QueryResponse(BaseModel):
# ────────────────────────────────────────────────────────────────────────────
-def _chunk(content: str, chunk_size: int = _CHUNK_SIZE) -> list[str]:
- return [content[i : i + chunk_size] for i in range(0, len(content), chunk_size)] or [content]
-
-
def _row_to_doc(row: Any) -> KBDocResponse:
return KBDocResponse(
id=row.id,
@@ -152,10 +148,10 @@ async def _synthesise(question: str, chunks: list[KBChunk]) -> str | None:
"/ingest", response_model=list[KBDocResponse], status_code=status.HTTP_201_CREATED, summary="Ingest document into knowledge base"
)
async def ingest(body: IngestRequest, db: DBSession, user: AuthUser) -> list[KBDocResponse]:
- chunks = _chunk(body.content)
+ chunks = chunk_text(body.content)
now = datetime.now(UTC)
rows = []
- for idx, chunk_text in enumerate(chunks):
+ for idx, chunk_content in enumerate(chunks):
doc_id = uuid.uuid4()
q = text("""
INSERT INTO aisoc_kb_documents (
@@ -171,7 +167,7 @@ async def ingest(body: IngestRequest, db: DBSession, user: AuthUser) -> list[KBD
title=body.title,
kind=body.doc_kind,
url=body.source_url,
- content=chunk_text,
+ content=chunk_content,
tags=body.tags or [],
idx=idx,
total=len(chunks),
diff --git a/services/api/app/services/kb_chunking.py b/services/api/app/services/kb_chunking.py
new file mode 100644
index 000000000..305ee60f2
--- /dev/null
+++ b/services/api/app/services/kb_chunking.py
@@ -0,0 +1,91 @@
+"""Knowledge-base document chunking.
+
+Pure, dependency-free text-chunking helpers used by the KB ingest endpoint
+(``POST /kb/ingest``). Kept separate from the endpoint module so the logic
+can be unit-tested without importing FastAPI / auth / DB dependencies.
+"""
+
+from __future__ import annotations
+
+import re
+
+CHUNK_SIZE = 800 # characters per chunk
+CHUNK_OVERLAP = 150 # overlap between consecutive chunks
+
+
+def chunk_text(
+ content: str,
+ chunk_size: int = CHUNK_SIZE,
+ overlap: int = CHUNK_OVERLAP,
+) -> list[str]:
+ """Sentence/paragraph-boundary-aware chunker with configurable overlap.
+
+ Strategy (recursive):
+ 1. Split on double-newlines (paragraph breaks) first.
+ 2. If a paragraph still exceeds chunk_size, split on sentence endings.
+ 3. If a sentence exceeds chunk_size, fall back to hard character split.
+
+ Each chunk overlaps the previous one by ``overlap`` characters so context
+ spans chunk boundaries and PostgreSQL ``to_tsvector`` stems complete words
+ rather than truncated fragments.
+
+ All produced units are guaranteed to be <= chunk_size characters before
+ the overlap tail is prepended, so no chunk can grow beyond
+ chunk_size + overlap in the worst case.
+ """
+ if not content:
+ return [content]
+
+ # ── Step 1: split into paragraphs ────────────────────────────────────
+ paragraphs = [p.strip() for p in re.split(r"\n\s*\n", content) if p.strip()]
+ if not paragraphs:
+ paragraphs = [content.strip()]
+
+ # Build atomic units, each guaranteed <= chunk_size. ``glue`` marks a
+ # unit that is a continuation of a hard-split run and therefore must be
+ # concatenated to its predecessor *without* an inserted space, so a token
+ # split across the boundary is reconstructed verbatim instead of corrupted
+ # (e.g. "CRITICAL_INDICATOR" must not become "CRITICAL_ INDICATOR").
+ units: list[tuple[str, bool]] = []
+ for para in paragraphs:
+ if len(para) <= chunk_size:
+ units.append((para, False))
+ else:
+ # Step 2: split on sentence boundaries (. ! ?)
+ sentences = re.split(r"(?<=[.!?])\s+", para)
+ for sent in sentences:
+ if len(sent) <= chunk_size:
+ units.append((sent, False))
+ else:
+ # Step 3: hard character split as last resort. Pieces are
+ # contiguous slices of the same run, so all but the first
+ # are glued to keep the original characters intact.
+ for piece_idx, i in enumerate(range(0, len(sent), chunk_size)):
+ units.append((sent[i : i + chunk_size], piece_idx > 0))
+
+ # ── Merge units into chunks with overlap ─────────────────────────────
+ chunks: list[str] = []
+ current = ""
+ for unit, glue in units:
+ sep = "" if glue or not current else " "
+ candidate = current + sep + unit
+ if len(candidate) <= chunk_size:
+ current = candidate
+ else:
+ if current:
+ chunks.append(current)
+ tail = current[-overlap:] if overlap and current else ""
+ # Re-seed with the overlap tail. A glued unit is contiguous with
+ # that tail, so no separator is inserted; otherwise a space is.
+ if tail:
+ new_current = tail + ("" if glue else " ") + unit
+ else:
+ new_current = unit
+ # If tail + unit still exceeds the limit (unit is near chunk_size),
+ # drop the tail — unit alone is always <= chunk_size (see above).
+ current = new_current if len(new_current) <= chunk_size else unit
+
+ if current:
+ chunks.append(current)
+
+ return chunks or [content]
diff --git a/services/api/tests/test_kb_chunker.py b/services/api/tests/test_kb_chunker.py
new file mode 100644
index 000000000..98af3394e
--- /dev/null
+++ b/services/api/tests/test_kb_chunker.py
@@ -0,0 +1,122 @@
+"""Tests for the boundary-aware KB chunker (issue #277).
+
+Imports the real implementation from ``app.services.kb_chunking`` so these
+tests guard the code that actually ships, not a copy.
+"""
+
+import random
+import string
+
+from app.services.kb_chunking import CHUNK_OVERLAP, CHUNK_SIZE, chunk_text
+
+
+def _chunk_old(content, chunk_size=CHUNK_SIZE):
+ """The original fixed-width chunker, kept only to contrast behaviour."""
+ return [content[i : i + chunk_size] for i in range(0, len(content), chunk_size)] or [content]
+
+
+def test_old_splits_mid_word():
+ text = "A" * 799 + " boundary_word " + "B" * 100
+ old = _chunk_old(text)
+ assert "boundary_word" not in old[0]
+ assert "boundary_word" in old[1]
+
+
+def test_new_keeps_word_intact():
+ text = "A" * 799 + " boundary_word " + "B" * 100
+ chunks = chunk_text(text)
+ assert any("boundary_word" in c for c in chunks)
+ assert not any(c.endswith("boundary_w") for c in chunks)
+
+
+def test_empty():
+ assert chunk_text("") == [""]
+
+
+def test_short_single_chunk():
+ t = "Short runbook entry."
+ assert chunk_text(t) == [t]
+
+
+def test_exact_size_single_chunk():
+ t = "x" * CHUNK_SIZE
+ assert len(chunk_text(t)) == 1
+
+
+def test_no_chunk_exceeds_size():
+ random.seed(99)
+ text = " ".join("".join(random.choices(string.ascii_lowercase, k=random.randint(3, 15))) for _ in range(600))
+ for c in chunk_text(text, chunk_size=800):
+ assert len(c) <= 800
+
+
+def test_sentence_boundary_not_split():
+ sentence = "The attacker leveraged a misconfigured S3 bucket to exfiltrate credentials. "
+ text = sentence * 15
+ for chunk in chunk_text(text, chunk_size=800):
+ assert chunk.rstrip()[-1] in ".!? "
+
+
+def test_paragraph_boundary_preserved():
+ text = "First paragraph about IR.\n\nSecond paragraph about hunting.\n\nThird about detection."
+ chunks = chunk_text(text, chunk_size=800)
+ assert len(chunks) == 1
+ assert "First" in chunks[0] and "Third" in chunks[0]
+
+
+def test_overlap_carries_context():
+ sentence = "Each runbook step must be followed in strict order. "
+ text = sentence * 20
+ chunks = chunk_text(text, chunk_size=800, overlap=150)
+ assert len(chunks) >= 2
+ for i in range(1, len(chunks)):
+ prev_words = chunks[i - 1][-150:].split()[:4]
+ assert any(w in chunks[i][:250] for w in prev_words)
+
+
+def test_long_paragraph_no_sentences():
+ word = "security " * 100
+ text = word + "\n\n" + word
+ chunks = chunk_text(text, chunk_size=800)
+ assert len(chunks) >= 2
+ for c in chunks:
+ assert len(c) <= 801
+
+
+def test_overlap_adds_total_chars():
+ sentences = ["Step %d: investigate alert before closing. " % i for i in range(50)]
+ text = " ".join(sentences)
+ no_ov = sum(len(c) for c in chunk_text(text, chunk_size=800, overlap=0))
+ with_ov = sum(len(c) for c in chunk_text(text, chunk_size=800, overlap=150))
+ assert with_ov >= no_ov
+
+
+def test_long_doc_multiple_chunks_all_within_limit():
+ long_text = ("Runbook step alpha. " * 10 + "\n\n") * 10
+ chunks = chunk_text(long_text, chunk_size=800)
+ assert len(chunks) >= 2
+ assert all(len(c) <= 800 for c in chunks)
+
+
+def test_overlap_default_constant():
+ assert CHUNK_OVERLAP > 0
+
+
+def test_hard_split_run_is_not_corrupted():
+ # A token longer than chunk_size with no whitespace/punctuation forces the
+ # hard-split fallback. Reassembly must keep characters contiguous: no space
+ # may be injected mid-token, and the original text must be reconstructable.
+ blob = "X" + "y" * 2500 + "Z"
+ chunks = chunk_text(blob, chunk_size=800, overlap=150)
+ assert all(len(c) <= 800 for c in chunks)
+ assert blob.startswith(chunks[0]) # first chunk is a true prefix
+ assert "y X" not in " ".join(chunks) # no stray separators inside the run
+
+
+def test_boundary_token_recovered_via_overlap():
+ # A keyword straddling a hard-split boundary must appear intact in at least
+ # one chunk thanks to the overlap, and must never be split by a space.
+ doc = "A" * 790 + " CRITICAL_INDICATOR_malware_c2_beacon " + "follows. " * 30
+ chunks = chunk_text(doc, chunk_size=800, overlap=150)
+ assert any("CRITICAL_INDICATOR_malware_c2_beacon" in c for c in chunks)
+ assert not any("CRITICAL_ INDICATOR" in c for c in chunks)