Skip to content

fix: enforce minimum hyperedge cardinality - #3

Draft
egarcia74 wants to merge 3 commits into
v8from
fix/hyperedge-minimum-cardinality
Draft

fix: enforce minimum hyperedge cardinality#3
egarcia74 wants to merge 3 commits into
v8from
fix/hyperedge-minimum-cardinality

Conversation

@egarcia74

@egarcia74 egarcia74 commented Sep 1, 2026

Copy link
Copy Markdown
Owner

Summary

Enforce Graphify's documented hyperedge contract: hyperedges represent group relationships and therefore require at least three surviving members. Pairwise relationships belong in the ordinary edge set.

The bug surfaced when unresolved members were pruned after semantic extraction. Valid 3+ member input could degrade into a one- or two-member hyperedge, then persist in semantic caches and graph.json.

Changes

  • Define one shared minimum-cardinality predicate (3 members).
  • Drop under-cardinality groups after semantic cleanup removes unknown/rationale nodes.
  • Prevent one- and two-member groups from entering semantic caches.
  • Heal invalid legacy groups during merged cache writes.
  • Drop groups that fall below three after graph member resolution.
  • Revalidate carried groups after incremental deleted-source pruning.
  • Revalidate existing and incoming groups at the attachment/export boundary.
  • Drop groups that collapse below three during entity deduplication.
  • Update legacy tests that previously codified one- and two-member hyperedges.
  • Add regression coverage for cache and persisted-graph healing.

Validation

  • Affected hyperedge/build/cache/export suite: 393 passed, 10 skipped.
  • Ruff over graphify and tests: PASS.
  • git diff --check: PASS.
  • Full Windows suite: 5,119 passed, 126 skipped, 29 failed. Remaining failures are unrelated platform/environment or generated-skill baseline failures (Windows symlink/FIFO/deleted-CWD behavior, shell-hook path handling, generated skill snapshots/install destinations); all hyperedge-related failures are resolved.

Origin

Observed against a real semantic corpus where under-cardinality cached hyperedges caused replay/provenance validation failures. A clean rebuild with the guards produced zero final or cached hyperedges below three members and zero final hyperedges lacking cache provenance.

Summary by CodeRabbit

  • Bug Fixes

    • Hyperedges with fewer than three valid members are now consistently removed.
    • Invalid, duplicate, dangling, or malformed hyperedge members are filtered out before saving or exporting.
    • Incremental graph updates now clean up hyperedges affected by deleted nodes.
    • Semantic cache updates no longer preserve undersized legacy hyperedges.
  • Tests

    • Expanded coverage for hyperedge validation, deduplication, merging, caching, cleanup, round trips, and varied member formats.

Treat hyperedges as 3+ member group relationships across semantic cleanup, cache persistence, deduplication, graph construction, incremental pruning, and attachment. Add regression coverage for invalid groups and legacy healing.
@egarcia74 egarcia74 self-assigned this Sep 1, 2026
@coderabbitai

coderabbitai Bot commented Sep 1, 2026

Copy link
Copy Markdown

Review Change Stack

Important

  • 🔍 Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Team

Run ID: 83e0642d-2dcf-4347-809f-a76eecbc53f5

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Team

Run ID: 129c97ac-42f1-4ae9-b7c1-f2b1dbaa44cd

📥 Commits

Reviewing files that changed from the base of the PR and between 33362d9 and 07330cd.

📒 Files selected for processing (17)
  • graphify/build.py
  • graphify/cache.py
  • graphify/dedup.py
  • graphify/export.py
  • graphify/semantic_cleanup.py
  • tests/test_build.py
  • tests/test_build_merge_hyperedges_and_prune.py
  • tests/test_cache.py
  • tests/test_carried_hyperedge_remap.py
  • tests/test_dedup_remaps_hyperedges.py
  • tests/test_extract_cli.py
  • tests/test_hyperedge_member_shapes.py
  • tests/test_hyperedge_roundtrip.py
  • tests/test_hypergraph.py
  • tests/test_merge_graphs_cli.py
  • tests/test_non_string_node_ids.py
  • tests/test_semantic_cleanup.py

Included review availability: Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

The change defines a three-member minimum for hyperedges. Graph construction, merge pruning, deduplication, semantic cleanup, cache writes, and export validation now remove undersized hyperedges. Tests update fixtures and coverage for the new rule.

Changes

Hyperedge cardinality enforcement

Layer / File(s) Summary
Graph lifecycle revalidation
graphify/build.py, graphify/dedup.py, graphify/semantic_cleanup.py, tests/test_build.py, tests/test_build_merge_hyperedges_and_prune.py, tests/test_dedup_remaps_hyperedges.py, tests/test_semantic_cleanup.py
Defines MIN_HYPEREDGE_MEMBERS = 3. Graph construction, merge pruning, semantic cleanup, and deduplication drop hyperedges with fewer than three surviving members.
Persistence and compatibility validation
graphify/cache.py, graphify/export.py, tests/test_cache.py, tests/test_hypergraph.py, tests/test_hyperedge_member_shapes.py, tests/test_hyperedge_roundtrip.py, tests/test_carried_hyperedge_remap.py, tests/test_extract_cli.py, tests/test_merge_graphs_cli.py, tests/test_non_string_node_ids.py
Cache and export paths filter undersized or invalid hyperedges. Tests update round-trip, normalization, merge, coercion, and legacy-cache coverage to use three-member hyperedges.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Merge Risk: 🟡 Moderate · up to 07330

The PR adds minimum-cardinality filtering, but duplicate or aliased members are counted before normalization in merge and cache paths, so a group with only two distinct members can still survive as a hyperedge. This is a bounded correctness issue in the contract enforcement and should be fixed or explicitly accepted before merge.

Sequence Diagram(s)

sequenceDiagram
  participant GraphBuilder
  participant SemanticCleanup
  participant CacheWriter
  participant Exporter
  GraphBuilder->>GraphBuilder: Revalidate surviving hyperedge members
  SemanticCleanup->>SemanticCleanup: Remove hyperedges below three members
  CacheWriter->>CacheWriter: Filter undersized hyperedges before writing
  Exporter->>Exporter: Validate and persist only valid candidates
Loading

Suggested reviewers: safishamsi, abhay-codes07

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.88% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 57 functions across 17 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: enforcing the minimum cardinality for hyperedges.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/hyperedge-minimum-cardinality

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@egarcia74
egarcia74 marked this pull request as ready for review September 1, 2026 10:02

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 07330cd272

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread graphify/dedup.py
Comment on lines +502 to +504
if len(rewired) >= 3:
kept.append(he)
hyperedges[:] = kept

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Normalize aliases before replacing the hyperedge list

When a valid three-or-more-member hyperedge uses the supported members or node_ids alias, the default build(..., dedup=True) path calls this function before build_from_json() performs alias normalization. Such an entry has no nodes list, so it is skipped here and then permanently deleted by hyperedges[:] = kept; the same extraction survives with dedup=False. Normalize the member aliases before filtering, or retain entries that this function cannot yet process.

Useful? React with 👍 / 👎.

Comment thread graphify/cache.py
Comment on lines 1476 to +1478
for h in (hyperedges or []):
if not _has_minimum_hyperedge_members(h):
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Canonicalize member aliases before filtering cache writes

For save_semantic_cache() callers that receive a valid hyperedge using the supported members or node_ids spelling, this predicate checks only canonical nodes and silently discards the group before it reaches the cache. Consequently a later cache replay loses that semantic relationship, and an otherwise hyperedge-only result can be treated as empty and retried. Normalize the aliases before both cardinality filters rather than rejecting them at this point.

Useful? React with 👍 / 👎.

@egarcia74 egarcia74 left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Ran CodeRabbit and verified both findings by hand against the diff. Two gaps in the new minimum-cardinality enforcement itself — details inline. Not blocking, just flagging before merge.

Comment thread graphify/cache.py
if src:
by_file[src]["edges"].append(e)
for h in (hyperedges or []):
if not _has_minimum_hyperedge_members(h):

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

_has_minimum_hyperedge_members(h) runs on the raw hyperedge here, before _normalize_hyperedge_members (which dedupes member refs and folds members/node_ids aliases onto nodes) ever runs — I checked cli.py's call into save_semantic_cache and confirmed normalization never happens first on this path. So {"nodes": ["a", "a", "b"]} has len == 3 and passes, even though it only has 2 distinct members — which defeats the invariant this PR adds. Suggest normalizing/deduping members before checking cardinality here (and at the other _has_minimum_hyperedge_members call a few lines down in this same function).

Comment thread graphify/build.py
candidate = he if surviving == he["nodes"] else {**he, "nodes": surviving}
if _has_minimum_hyperedge_members(candidate):
final_hyperedges.append(candidate)
G.graph["hyperedges"] = final_hyperedges

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

This revalidation (dedupe + filter to surviving nodes + _has_minimum_hyperedge_members) is correct, but it's nested entirely inside if prune_sources: above. A normal incremental --update that doesn't delete/exclude any files skips this safety net entirely, so a carried hyperedge that degrades — e.g. via the semantic re-key step (~line 934) collapsing two distinct ids onto the same one without a subsequent re-dedupe — can slip through when no prune is involved. Since the goal of this PR is enforcing the 3+ member invariant universally, consider moving this block out of the if prune_sources: gate so it always runs before merge_raw_extraction/build_merge return.

Minor/separate nit while in this area: dedup.py's _remap_hyperedge_members (line ~502) still hardcodes len(rewired) >= 3 instead of the new MIN_HYPEREDGE_MEMBERS/_has_minimum_hyperedge_members this PR introduces as the canonical check — same value today, but now a second source of truth for the constant.

Neither existing test (test_hyperedge_member_shapes.py, test_build_merge_hyperedges_and_prune.py) currently covers the duplicate-raw-member case, so both gaps pass CI as-is.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

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