feat(extractor): recognise self-populated owned-collection elements as self-owned (#229)#239
Conversation
|
Warning Review limit reached
Next review available in: 28 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughThe extractor recognizes subscriptions to elements of self-populated class collections and suppresses ChangesOwned collection element 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
Possibly related PRs
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
| { | ||
| _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 |
There was a problem hiding this comment.
💡 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".
| if (expr is ObjectCreationExpressionSyntax or ImplicitObjectCreationExpressionSyntax) | ||
| return true; |
There was a problem hiding this comment.
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 👍 / 👎.
| IdentifierNameSyntax => true, // CreateData() | ||
| MemberAccessExpressionSyntax { Expression: ThisExpressionSyntax } => true, // this.CreateData() |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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
📒 Files selected for processing (4)
.github/workflows/ci.ymldocs/notes/field-notes-patterns.mdfrontend/roslyn/OwnSharp.Extractor/Program.csfrontend/roslyn/samples/OwnedCollectionElementSample.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 |
|
@coderabbitai review |
✅ Action performedReview finished.
|
ad445dd to
c5b187c
Compare
…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
c5b187c to
88417e6
Compare
Что и зачем
Расширяет self-owned-source исключение на sub-issue #229 (часть c родительского #221): подписка на элемент коллекции, которую класс сам заполнил (
Items1 = CreateData(); foreach (var m in Items1) m.PropertyChanged += ...), больше не помечается OWN001. Коллекция и её элементы разделяют время жизни конструирующего объекта, поэтомуelement.Event += ...— тот же собираемый GC self-цикл, что и сконструированное поле (FP из MaterialDesignListsAndGridsViewModel.cs, найденный oracle-sweep по #201).Реализовано строго в зафиксированных «Design guardrails» issue, без расширения (
IsOwnedCollectionElementSource): приёмник+=должен по СИМВОЛУ связываться с переменнойforeach; итерируемая коллекция — bare/this-квалифицированное поле/свойство ЭТОГО класса; каждое место заполнения этого члена — own-produced значение (MemberPopulatedByOwnFactory+IsOwnProducedValue): прямое создание объекта / инициализатор коллекции, либо вызов метода этого класса с implicit/this-получателем. Ctor-параметр, инъектированное поле или service-located вызов (_service.GetData()) отменяют доказательство — инъектированная коллекция сохраняет честное предупреждение. Полностью семантично, без текстового матчинга.Тип изменения
Как проверено
python tests/run_tests.py(276/276 ownir, все зелёные)ruff check .иmypy(чисто)OwnedCollectionElementSample.cs: 3 тихих позитива (own factory в свойство, поле-инициализатор коллекции,newв ctor), 4 контроля помечены (поле из ctor-параметра;foreachпрямо по параметру-коллекции; service-located источник; член, также переприсвоенный инъекцией)Связанные issue
Closes #229. Refs #221 (родитель, контекст). Sub-issue #227 (часть a) идёт отдельным PR (#237).
Чеклист
OwnedCollectionElementSample.cs+ wpf-extractor job, обе стороны) и задокументировано вdocs/notes/field-notes-patterns.md(entry 15, shape c)feat:)🤖 Generated with Claude Code
Generated by Claude Code
Summary by CodeRabbit
Bug Fixes
OWN001warnings for non-timer+=event subscriptions when the handler receiver comes from aforeachloop element backed by a class-owned collection.Documentation
#229is shipped (alongside#227for associated-object behavior).Tests / Samples
OwnedCollectionElementSampledemonstrating both silent and REQUIRED (flagged) cases for#229verification.