Skip to content

docs: proposal rag based design security guidelines - #114

Open
iamsreec wants to merge 5 commits into
mainfrom
sc/rag-design-security-guidelines
Open

iamsreec wants to merge 5 commits into
mainfrom
sc/rag-design-security-guidelines

Conversation

@iamsreec

@iamsreec iamsreec commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

Summary

Security analysis currently loads large threat-catalog sections directly into the model context. Add a vector-backed retrieval layer that selects only the catalog entries relevant to the current architecture, attack surfaces, and analysis phase.

The complete catalog must remain the authoritative source. Vector retrieval should optimize candidate discovery without silently excluding required coverage.

Design Sketch

  • Parse the canonical catalog into independently retrievable entries.
  • Store embeddings with:
  • canonical threat/scenario ID;
  • source-catalog hash and schema version;
  • threat-discovery fields;
  • mitigation fields;
  • source references.
  • Step C performs bounded semantic retrieval using architecture and attack-surface queries.
  • Step D loads mitigation data by the exact threat IDs selected in Step C.
  • Deduplicate results by canonical ID and record retrieved IDs in the phase artifact.
  • Validate index freshness before every analysis run

Changes

  • Context budget (new §5A): a context boundary at every phase, phase-scoped handoff files (whole tables/columns dropped, never rows), and budget-sized batches within a phase. Each call is budgeted for
    input, output, and one retry. The 61-scenario and every-threat-once checks still run on the merged result.
  • Measurements (§2): Llama 3 token counts for all five examples. Phase D's input files are 22–42K tokens; its catalog slice is 3–7K; Phase C's Scenario Coverage (3–4.5K) isn't used by Phase D.
  • Real-run evaluation (§9.A): peak context, total tokens, retries, and quality (scenario dispositions, threat set, owners, emitted guidance) across four arms, n = 3, before each part is built.
  • Search budget (§6): max_items comes from each batch's remaining budget and always wins; deterministic allocation with stated tie-breaks.
  • Ranked snapshot freshness (§6): separate checks for baseline, additions, and per-threat order.
  • Snapshot validation (§5): strict structure checks, and the hash is of the validated bytes (from feat(security-analysis): record and verify the OWASP catalog each phase reads #154 review).
  • Phasing (§8): PR 1 provenance (feat(security-analysis): record and verify the OWASP catalog each phase reads #154), PR 2 context budget, PR 3 ranking (only if §9.0 shows ordering changes Phase D's output).

Notes

Code follows in separate PRs. #154 stays limited to snapshots and provenance. Per-call usage logging (§9.A) is needed before PR 2's measurements.

@iamsreec iamsreec self-assigned this Oct 13, 2026
@iamsreec

Copy link
Copy Markdown
Member Author

@araujof Can you share your feedback on the design.

Signed-off-by: Sai Sree Laya Chukkappalli <saisreelaya.chukkapalli@gmail.com>
@iamsreec
iamsreec force-pushed the sc/rag-design-security-guidelines branch from 3719082 to 295bde0 Compare October 13, 2026 18:29
@araujof araujof added this to the 0.3.0 milestone Oct 18, 2026
@terylt

terylt commented Oct 21, 2026

Copy link
Copy Markdown

Hi @iamsreec,

Overall, I think this is pretty good. A few things I would recommend:

  1. Add context up front for the reader about exactly what is trying to be done. AI knows everything and so it can leave out things that a human reader may not know. It'll make it easier to read.
  2. I think the approach seems reasonable. 1 & 2 look to be the right approach. 3 probably needs some benchmarking for accuracy to get a sense of how good it is at retrieving IDs and prioritizing them.

Findings

1. Rebase onto main. The branch predates security_analysis_checkpoint.py and guidance_merge.py, so none of the file:line references resolve on it. They do resolve on main, and the ones I checked are correct (:569, :607-611, :729-742, :942, guidance_merge.py:201-213). Readers of the PR will have the same trouble I did.

2. The Phase C query is built from the table Phase C is writing. §6 says queries are "built from validated artifact fields, not model prose", and Phase C queries use Attack Surfaces rows. Attack Surfaces is a Phase C table (the "C" schema in security_analysis_checkpoint.py), so when the ranking is needed those rows have not been validated. Either Phase C needs two steps (surfaces, then retrieval, then dispositions), which the checkpoint does not support today because it validates the whole phase at once, or the claim does not hold for Phase C. Could the doc say which? Phase D is fine: its queries come from Threat Instances, which Phase C has already checkpointed.

3. No evidence yet that the current approach falls short. The numbers in §2 are catalog and token sizes, not retrieval quality. The motivating example (T1 classed ASI01 with its real mitigations in ASI03 and ASI02) is a judgement that §10 step 3 plans to confirm later. 11 to 15K tokens is not large for current models. Could §9 add a baseline: the same threats run through Phase D with and without augmentation, scored against the same labels? Without it, recall@k shows that retrieval finds relevant items but not that Phase D would otherwise have missed them.

4. The evaluation set is one example. Thresholds tuned on hr-agent's 14 threats will likely fit hr-agent. Labelling a second example from the other four and checking that top_k and min_score still hold would make the result more convincing.

5. The N/A pre-screen could anchor the model. It is described as a hint only, but showing the model a scenario as probably N/A pushes it toward that answer. The §9 gate measures whether the screen separates threat-cited scenarios from N/A ones, not whether the hint changes the model's dispositions. How would that be tested? If there is no good answer, shipping step 7 and leaving step 8 open seems the safer scope.

6. Final ordering after merging queries is unspecified. The bounding order is top_k per query, min_score, dedupe by max score, then max_items. It does not say whether the cap applies to a single list sorted by score or per threat. In Phase D that decides which threats lose augmentation when the cap is hit.

Nits

  • §10 checks consulted.D.mitigation_ids, but the §5 schema names the field baseline_ids.
  • §2's "361 retrievable items" is two separate indexes (61 scenarios and 300 mitigation items), which §6 makes clear but §2 does not.
  • §5's "~4.4K tokens saved, 28%" compares against loading all ten categories, but enforcement_mapping.md already instructs Phase D to load only applicable ones. The real change is that the tool enforces the set rather than the prompt, which is worth saying directly.
  • Open question 2: if the index is derived and gitignored, everyone running Phase C or D needs the model weights. That seems like a bigger cost than 555 KB of .npz in review, but it is the author's call.

@iamsreec

Copy link
Copy Markdown
Member Author

@terylt, Thank you for sharing the feedback. Modified the sketch based on it.

Signed-off-by: Sai Sree Laya Chukkappalli <saisreelaya.chukkapalli@gmail.com>
Signed-off-by: Sai Sree Laya Chukkappalli <saisreelaya.chukkapalli@gmail.com>
Signed-off-by: Sai Sree Laya Chukkappalli <saisreelaya.chukkapalli@gmail.com>
araujof
araujof previously approved these changes Nov 9, 2026

@araujof araujof left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This looks ready as a design proposal. Keeping the baseline catalog set intact while checking whether ranking changes Phase D decisions makes sense. I have two questions about the search budget and how ranked and augmented snapshots pass the freshness check.

- **Two separate indexes** so a scenario query can never return a mitigation item — Phase C field discipline enforced structurally.
- Vectors L2-normalized, so the one surviving absolute threshold (`novel_floor`) is comparable across runs. Deterministic ordering → rebuilds are byte-identical.
- **Embedding text remains an open question.** The initial draft used `f"{entry.name}: {item_text}"` because short clauses such as *"Apply version control."* lack context. However, adding the same category name to roughly 30 items may reduce within-category separation and make cross-category comparison depend too heavily on category labels. Measure prefixed and unprefixed text before choosing a format (open question 1) and before tuning other parameters.
- **Only `search` is bounded:** apply per-query `top_k`, deduplicate by canonical ID while keeping the maximum score, then apply global `max_items` with at least one result per query. `top_k` limits candidates before deduplication; `max_items` limits total added context. The per-query floor prevents a few high-scoring threats from consuming the full budget. Results stay grouped by query and carry the originating threat (`"threat": "T12"` in §6). Phase C uses the same rule for each `Attack Surfaces` row.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

max_items is described as a global cap, but the test at line 574 keeps one hit per query even when queries outnumber it. With distinct hits, those rules conflict. Which one wins? It would also help to state how remaining slots and ties are assigned so repeated runs get the same result.


**Key invariant and regression tests:**
- **`rank` is order-only:** for every input set, output is a permutation with the same multiset of IDs. This directly tests the §3 invariant.
- Phase D's ranked snapshot contains exactly the PR 1 snapshot's items; with the index absent it is byte-identical to the PR 1 snapshot.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Does this exact-set assertion apply only to rank-only mode? Step 7 also writes cross-category additions into the snapshot, so the augmented version should have more than PR 1's items. The §5 freshness check compares the snapshot to the canonical projection; please spell out how it accepts reordering and additions while still catching missing or changed baseline items.

@araujof
araujof dismissed their stale review November 9, 2026 03:20

Revisiting the context-reduction goal. The spec needs smaller handoffs, context budgets and measurements of full workflow token use before approval.

@araujof araujof left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Could we revisit section 0.1 before merging? Reducing context use was part of the reason for this proposal, but the current design makes context capacity a non-goal. Ranking keeps the same entries, and cross-category search adds more. The catalog fitting in the window doesn't tell us how much the whole analysis consumes.

I counted the saved files for the five examples with a Llama tokenizer. The architecture, questionnaire and threat model together came to about 16-35K tokens; Phase D's input files came to 26-46K before chat history, earlier source reads, output and retries. These are file counts; we still need measurements from actual runs.

Please update the spec with a plan for smaller phase handoffs, batches that don't keep accumulating in the same context, and a total context budget with room for output and retries. Keep checkpoint validation of all 61 scenarios across the batches, and spell out how retrieved additions fit within the budget. Add a comparison of peak context, total tokens and analysis quality on real example runs, and update this PR's description to match. The code can follow in separate PRs; #154 can stay focused on snapshots and provenance.

Signed-off-by: Sai Sree Laya Chukkappalli <saisreelaya.chukkapalli@gmail.com>
@iamsreec

iamsreec commented Nov 12, 2026 •

Copy link
Copy Markdown
Member Author

I reproduced your counts (Llama 3): A–C is 16–34K, Phase D input is 22–42K, and the catalog is only 3–7K of that. So the savings come from handoffs and batching, not the catalog.

§0.1: context use is now a goal.
§5A (new): a context boundary per phase, phase-scoped handoffs (dropping Scenario Coverage alone saves 14–26% of Phase D's input), and budget-sized batches. All 61 scenarios are still validated on the merged result. Additions use whatever budget is left.
§9.A (new): peak context, total tokens, retries and quality on fresh A–D runs, n = 3.
Split into three PRs: provenance (#154), then context, then ranking. Description updated.
Line 317 The cap wins. Each query gets its best hit first, in order of score, then severity, then threat ID. Any remaining slots go by global score, with ties broken by canonical ID. Queries left out are recorded in budget_exhausted. The test is updated to match.
Line 573 Yes I held in rank-only mode. The snapshot is now split into baseline, augmented and per-threat order:

  • baseline must equal the current projection
  • Each augmented item must match the catalog, come from a non-applicable category, and fit within max_items.
  • Each order list must be a permutation of baseline.
  • §10 has tests for each check.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants