effect icon indicating copy to clipboard operation
effect copied to clipboard

`Cache.make` shouldn't return an `Effect` which has an `Environment` requirement

Open arturaz opened this issue 9 months ago • 2 comments

What version of Effect is running?

3.19.19

What steps can reproduce the bug?

This should be possible:

  const doToolCall: Effect.Effect<string, never, MyDeps>

        const cache = Effect.runSync(
          Cache.make({
            capacity: 1000,
            timeToLive: '5 minutes',
            lookup: (_key: ToolCallCacheKey) => doToolCall,
          }),
        )

Making the cache doesn't need MyDeps, doing the lookups does.

What is the expected behavior?

Cache.make should look like:

export const make: <Key, Value, Error = never, Environment = never>(
  options: {
    readonly capacity: number
    readonly timeToLive: Duration.DurationInput
    readonly lookup: Lookup<Key, Value, Error, Environment>
  }
) => Effect.Effect<Cache<Key, Value, Error>, never, never> 

What do you see instead?

No response

Additional information

No response

arturaz avatar Feb 23 '26 13:02 arturaz

I traced through the implementation and I think I understand the root cause. Posting my analysis in case it's useful before submitting a PR.

Root cause: makeWith in internal/cache.ts (line 710) calls core.context<Environment>() eagerly during cache construction. This captures the full environment context at creation time, then provides it to the lookup function later via core.provideContext(this.context) in lookupValueOf. This forces Environment into the construction effect's type even though it's only needed at lookup time.

Two possible approaches:

  1. Add Environment as a 4th type parameter to Cache<Key, Value, Error, Environment> (defaulting to never). Remove the eager context capture. Let the environment flow through naturally at lookup time. Methods like get, getEither, refresh would return Effect<..., ..., Environment>. Construction returns Effect<Cache<Key, Value, Error, Environment>, never, never>.

  2. Same as (1) but also apply the fix to ScopedCache.make, which has the same issue (line 119-125 of ScopedCache.ts).

Both approaches are breaking at the type level: downstream code that explicitly references Cache<Key, Value, Error> would need the 4th parameter when Environment is non-never. Existing code with Environment = never (the default) would be unaffected.

Is approach (1) the right direction, or would you prefer a different design? Happy to submit a PR once there's alignment on the approach.

blackwell-systems avatar Apr 28 '26 21:04 blackwell-systems

In v3 this is by design. In v4 you can choose where the environment is pulled from (construction vs request time).

tim-smart avatar Aug 02 '26 21:08 tim-smart