Skip to content

Align compiled singleton PostConstruct lifecycle#138

Draft
koriym wants to merge 1 commit into
ray-di:1.xfrom
koriym:cache-singleton-before-postconstruct
Draft

Align compiled singleton PostConstruct lifecycle#138
koriym wants to merge 1 commit into
ray-di:1.xfrom
koriym:cache-singleton-before-postconstruct

Conversation

@koriym

@koriym koriym commented Jul 15, 2026

Copy link
Copy Markdown
Member

Summary

  • cache compiled singleton instances before invoking PostConstruct, matching Ray.Di runtime semantics
  • make the active CompiledInjector its own InjectorInterface singleton so lifecycle re-entry uses the same singleton cache
  • remove a singleton from the cache when its PostConstruct throws, allowing a clean retry

Root cause

Generated singleton scripts cached instances only after PostConstruct completed. A lifecycle method that resolved a dependency back to the singleton therefore started constructing the same object again. In addition, injected InjectorInterface values were separate CompiledInjector instances, so re-entry did not share the active injector's singleton cache.

Behavior

The generated script now provisionally caches the constructed singleton, invokes PostConstruct, and removes that entry before rethrowing any Throwable. This rollback is intentionally local to the singleton whose lifecycle method failed. Other successfully created singletons and external side effects are not treated as a transaction, consistent with the container's existing resolution model.

Validation

  • composer cs-fix
  • composer cs
  • composer test — 99 tests, 187 assertions
  • PHPStan — no errors
  • Psalm under PHP 8.4 — no errors, 99.8246% inferred types
  • composer coverage — 100% classes, methods, and lines
  • targeted manual mutation checks: removing provisional caching, rollback, or injector self-caching makes the new regression tests fail

composer tests reaches Psalm through its PHP 8.5 shebang and currently stops on Psalm's own deprecated SplObjectStorage::attach() call. Running the same Psalm binary explicitly with PHP 8.4 succeeds; the PHPUnit, coding-standard, and PHPStan phases also pass independently on PHP 8.5.

Summary by CodeRabbit

  • Bug Fixes

    • Improved singleton initialization during post-construction lifecycle events.
    • Ensured dependencies can access singleton instances while initialization is running.
    • Prevented partially initialized singletons from being retained when initialization fails.
    • Failed initialization now supports safe retries and subsequent reuse of the successfully initialized instance.
  • Tests

    • Added coverage for singleton availability, injector resolution, initialization failures, retries, and instance reuse.

@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6bc6bd28-9d0f-4285-a5f8-53fe1292ef6c

📥 Commits

Reviewing files that changed from the base of the PR and between eafc543 and 63c40b7.

📒 Files selected for processing (6)
  • src/CompiledInjector.php
  • src/InstanceScript.php
  • tests/Fake/FakeFailingPostConstructSingleton.php
  • tests/Fake/FakePostConstructDependent.php
  • tests/Fake/FakePostConstructSingleton.php
  • tests/SingletonPostConstructTest.php

📝 Walkthrough

Walkthrough

Compiled injectors now cache the injector instance during wakeup. Singleton instances are cached before PostConstruct, removed when initialization throws, and covered by tests for dependency access, identity reuse, and retry behavior.

Changes

Singleton lifecycle handling

Layer / File(s) Summary
Injector cache initialization
src/CompiledInjector.php
CompiledInjector stores itself in the singleton map under InjectorInterface before registering its autoloader.
Post-construct singleton lifecycle
src/InstanceScript.php, tests/Fake/*, tests/SingletonPostConstructTest.php
Generated singleton code caches instances before PostConstruct, removes them when initialization throws, and verifies successful reuse and retry behavior.
Estimated code review effort: 3 (Moderate) ~20 minutes

Possibly related PRs

  • ray-di/Ray.Compiler#115: Introduced the CompiledInjector and InstanceScript implementation extended by these lifecycle changes.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly reflects the main change: aligning compiled singleton PostConstruct lifecycle behavior.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@koriym

koriym commented Jul 15, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor
✅ 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.

@codecov

codecov Bot commented Jul 15, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (eafc543) to head (63c40b7).

Additional details and impacted files
@@             Coverage Diff             @@
##                 1.x      #138   +/-   ##
===========================================
  Coverage     100.00%   100.00%           
- Complexity        95        99    +4     
===========================================
  Files             11        11           
  Lines            238       253   +15     
===========================================
+ Hits             238       253   +15     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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.

1 participant