Skip to content

feat(extractor): recognise self-populated owned-collection elements as self-owned (#229)#239

Merged
PhysShell merged 1 commit into
mainfrom
claude/owned-collection-229
Jul 12, 2026
Merged

feat(extractor): recognise self-populated owned-collection elements as self-owned (#229)#239
PhysShell merged 1 commit into
mainfrom
claude/owned-collection-229

Conversation

@PhysShell

@PhysShell PhysShell commented Jul 11, 2026

Copy link
Copy Markdown
Owner

Что и зачем

Расширяет self-owned-source исключение на sub-issue #229 (часть c родительского #221): подписка на элемент коллекции, которую класс сам заполнил (Items1 = CreateData(); foreach (var m in Items1) m.PropertyChanged += ...), больше не помечается OWN001. Коллекция и её элементы разделяют время жизни конструирующего объекта, поэтому element.Event += ... — тот же собираемый GC self-цикл, что и сконструированное поле (FP из MaterialDesign ListsAndGridsViewModel.cs, найденный oracle-sweep по #201).

Реализовано строго в зафиксированных «Design guardrails» issue, без расширения (IsOwnedCollectionElementSource): приёмник += должен по СИМВОЛУ связываться с переменной foreach; итерируемая коллекция — bare/this-квалифицированное поле/свойство ЭТОГО класса; каждое место заполнения этого члена — own-produced значение (MemberPopulatedByOwnFactory + IsOwnProducedValue): прямое создание объекта / инициализатор коллекции, либо вызов метода этого класса с implicit/this-получателем. Ctor-параметр, инъектированное поле или service-located вызов (_service.GetData()) отменяют доказательство — инъектированная коллекция сохраняет честное предупреждение. Полностью семантично, без текстового матчинга.

Тип изменения

  • feat — новая возможность

Как проверено

  • python tests/run_tests.py (276/276 ownir, все зелёные)
  • ruff check . и mypy (чисто)
  • Реальный экстрактор (.NET 8) на OwnedCollectionElementSample.cs: 3 тихих позитива (own factory в свойство, поле-инициализатор коллекции, new в ctor), 4 контроля помечены (поле из ctor-параметра; foreach прямо по параметру-коллекции; service-located источник; член, также переприсвоенный инъекцией)
  • Диф вывода экстрактора old vs new по всему набору сэмплов — байт-в-байт идентичен (ноль регрессий); все ассерты wpf-extractor CI проходят в обе стороны

Связанные issue

Closes #229. Refs #221 (родитель, контекст). Sub-issue #227 (часть a) идёт отдельным PR (#237).

Чеклист

  • изменение покрыто CI-ассертами (OwnedCollectionElementSample.cs + wpf-extractor job, обе стороны) и задокументировано в docs/notes/field-notes-patterns.md (entry 15, shape c)
  • README/docs обновлены при необходимости (field-notes entry 15 помечен как shipped для shape c)
  • коммиты в conventional-commit стиле (feat:)

🤖 Generated with Claude Code


Generated by Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Reduced false-positive OWN001 warnings for non-timer += event subscriptions when the handler receiver comes from a foreach loop element backed by a class-owned collection.
    • The exemption now requires the owning member to be populated exclusively with provably own-produced values; injected/service/mixed/partial/seeded-from-injected scenarios remain flagged.
  • Documentation

    • Updated maintenance notes clarifying that the self-owned collection shape for #229 is shipped (alongside #227 for associated-object behavior).
  • Tests / Samples

    • Added OwnedCollectionElementSample demonstrating both silent and REQUIRED (flagged) cases for #229 verification.

@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@PhysShell, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 28 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 66d729d3-9b4c-4bf1-8eda-6b93e783f6d3

📥 Commits

Reviewing files that changed from the base of the PR and between c5b187c and 88417e6.

📒 Files selected for processing (4)
  • .github/workflows/ci.yml
  • docs/notes/field-notes-patterns.md
  • frontend/roslyn/OwnSharp.Extractor/Program.cs
  • frontend/roslyn/samples/OwnedCollectionElementSample.cs
📝 Walkthrough

Walkthrough

The extractor recognizes subscriptions to elements of self-populated class collections and suppresses OWN001. New samples cover accepted and rejected ownership sources, while CI assertions and field notes document the behavior.

Changes

Owned collection element exemption

Layer / File(s) Summary
Extractor ownership analysis
frontend/roslyn/OwnSharp.Extractor/Program.cs
Adds collection-source, population-site, partial-type, and own-produced-value checks, then applies the exemption during event-subscription analysis.
Collection ownership sample cases
frontend/roslyn/samples/OwnedCollectionElementSample.cs
Adds silent self-produced collection cases and flagged constructor-parameter, service-located, forwarding-factory, seeded, mixed-population, and partial-class controls.
CI validation and field notes
.github/workflows/ci.yml, docs/notes/field-notes-patterns.md
Adds sample extraction, issue 229 assertions, consolidated CI output, and maintenance notes for the exemption.

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

Sequence Diagram(s)

sequenceDiagram
  participant OwnedCollectionElementSample
  participant OwnSharpExtractor
  participant CI
  OwnedCollectionElementSample->>OwnSharpExtractor: provide collection subscription samples
  OwnSharpExtractor->>CI: report OWN001 findings
  CI->>CI: verify silent and flagged cases
Loading

Possibly related PRs

  • PhysShell/Own.NET#28: Both changes extend OWN001 event-subscription analysis and update CI assertions, but address different subscription patterns.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise, specific, and accurately summarizes the main extractor change for #229.
Description check ✅ Passed It fills the required sections with purpose, change type, verification, linked issue, and checklist items.
Linked Issues check ✅ Passed The extractor, samples, docs, and CI assertions match #229's self-populated collection pattern and keep injected sources flagged.
Out of Scope Changes check ✅ Passed The workflow, sample, extractor, and docs updates all support #229 and no unrelated changes are evident.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/owned-collection-229

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.

{
_injected = injected;
foreach (var m in _injected)
m.PropertyChanged += OnChanged; // OWN001: injected collection
public ParamCollectionViewModel(IEnumerable<Model> models)
{
foreach (var m in models)
m.PropertyChanged += OnChanged; // OWN001: parameter collection
_service = service;
_items = _service.GetData();
foreach (var m in _items)
m.PropertyChanged += OnChanged; // OWN001: service-located source
{
_items = CreateData();
foreach (var m in _items)
m.PropertyChanged += OnChanged; // OWN001: _items also injected below

@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: a87294208c

ℹ️ 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 on lines +1094 to +1095
if (expr is ObjectCreationExpressionSyntax or ImplicitObjectCreationExpressionSyntax)
return true;

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 Reject externally seeded new collections

When a member is assigned new List<Model>(models) or new ObservableCollection<Model>(service.GetData()), this treats the value as own-produced solely because the collection object is newly allocated. The foreach exemption then suppresses OWN001 even though the subscribed event sources are the injected elements, which can outlive the subscriber and retain its handler; object creations need to prove their constructor/initializer elements are own-created or be rejected.

Useful? React with 👍 / 👎.

Comment on lines +1104 to +1105
IdentifierNameSyntax => true, // CreateData()
MemberAccessExpressionSyntax { Expression: ThisExpressionSyntax } => true, // this.CreateData()

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 Prove same-class factories before trusting them

A same-class helper like GetData() => _service.GetData() satisfies this switch when called as Items = GetData();, so MemberPopulatedByOwnFactory marks the collection owned and drops the foreach OWN001. That wrapper still returns service/injected models with unknown lifetime, so accepting any implicit/this call without inspecting or annotating its return introduces false negatives for leak-producing subscriptions.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@frontend/roslyn/OwnSharp.Extractor/Program.cs`:
- Around line 1049-1083: Update MemberPopulatedByOwnFactory to scan all
declarations of the containing partial type, not only clsNode.DescendantNodes().
Include variable initializers, property initializers, and simple assignments
from sibling partial declarations while preserving the existing
any/IsOwnProducedValue validation and early rejection behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: d4cb2a96-a2ad-4a1b-9daf-54d202e24bdb

📥 Commits

Reviewing files that changed from the base of the PR and between b1ee961 and a872942.

📒 Files selected for processing (4)
  • .github/workflows/ci.yml
  • docs/notes/field-notes-patterns.md
  • frontend/roslyn/OwnSharp.Extractor/Program.cs
  • frontend/roslyn/samples/OwnedCollectionElementSample.cs

Comment thread frontend/roslyn/OwnSharp.Extractor/Program.cs
{
_items = new List<Model>(injected);
foreach (var m in _items)
m.PropertyChanged += OnChanged; // OWN001: seeded from injected elements
_service = service;
_items = MakeData();
foreach (var m in _items)
m.PropertyChanged += OnChanged; // OWN001: factory forwards injected data
{
_items = CreateData();
foreach (var m in _items)
m.PropertyChanged += OnChanged; // OWN001: _items also injected in the sibling partial
@github-actions

Copy link
Copy Markdown

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@PhysShell
PhysShell force-pushed the claude/owned-collection-229 branch from ad445dd to c5b187c Compare July 12, 2026 09:05
…s self-owned (#229)

Subscribing to an element of a collection the class itself populated —
`Items1 = CreateData(); foreach (var m in Items1) m.PropertyChanged += ...` — was
tiered "injected" and warned OWN001 (the MaterialDesign ListsAndGridsViewModel FP
from the issue #201 sweep). The collection and its elements share the constructing
object's lifetime, so `element.Event += ...` is the same collectable self-cycle as
a constructed field.

The exemption is deliberately narrow, within the issue's fixed guardrails
(`IsOwnedCollectionElementSource`): the `+=` receiver must bind by SYMBOL to a
`foreach` loop variable; the iterated collection must be a bare/`this`-qualified
field or property of THIS class; and every population site of that member must be an
own-produced value — a direct object creation / collection initializer whose
constructor args and elements are themselves own-produced, or an invocation of an
own factory (a method of this class with an implicit/`this` receiver) whose body
provably returns only own-produced values. A ctor parameter, an injected field, a
service-located call (`_service.GetData()`), a seeded `new List<T>(injected)`, or a
forwarding factory denies the proof — the injected collection keeps today's honest
warning. Population sites are scanned across every partial declaration of the type.

Pinned by OwnedCollectionElementSample.cs: three silent positives and seven flagged
controls (injected field, parameter foreach, service-located, mixed, seeded-new,
forwarding factory, partial-class sibling write), wired into the wpf-extractor CI job
with assertions both ways.

Verified locally with the real extractor (.NET 8): the sample yields exactly the
seven control warnings, all three positives silent; a full-sample-set diff of old vs
new extractor output is byte-identical (zero regression). Gates: run_tests 276/276,
ruff, mypy, yaml all green.

Closes #229

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01U2AWb9N2VUsby2XpdftBcu
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.

Self-owned source (c): subscription to elements of a self-populated collection field

3 participants