Skip to content

RequestResolver.fromEffect runs every entry with the first caller's context #9553

Closed

Description

@wmaurer

What happens

RequestResolver.fromEffect runs f(entry) once for each entry. But each run gets the context of the batch fiber, not the context of the entry. The batch fiber has the context of the first caller in the batch. So if two callers provide different values for a service, and f reads that service, both callers get the value of the first caller. There is no error. fromEffect handles one entry at a time, so its signature does not suggest that entries share a context.

The runAll of every resolver also gets one context for the whole batch. Which caller this context comes from depends on the order in which the callers arrive. If collectWhile ends a batch, for example with RequestResolver.batchN, runAll runs with the context of the caller that filled the batch. If not, it runs with the context of the caller that created the batch.

SqlResolver puts callers inside a transaction and callers outside a transaction into separate batches. But it runs execute with the context of the first caller. So callers with different values for any other service share one execute call, and this call uses the services of the first caller.

Issue #9551 describes the same problem in EmbeddingModel.make. #9552 fixes it there with a batch key that the provider gives. Context that the key does not return still comes from the first caller, for example FetchHttpClient.RequestInit. #9552 leaves this case to this issue.

Reproduction

Effect main at 4cddd3c (effect 4.0.5). Save the code as a .ts file inside the repository and run it with node.

import { SqliteClient } from "@effect/sql-sqlite-node"
import { Context, Effect, Exit, Option, Request, RequestResolver, Schema } from "effect"
import { SqlClient, SqlResolver } from "effect/sql"

class Tenant extends Context.Service<Tenant, string>()("repro/Tenant") {}
const tenant = Effect.map(Effect.serviceOption(Tenant), Option.getOrElse(() => "none"))

interface Get extends Request.Request<string> {
  readonly _tag: "Get"
  readonly id: number
}
const Get = Request.tagged<Get>("Get")

// 1. fromEffect: each entry reads Tenant.
const fromEffect = RequestResolver.fromEffect<Get>((entry) =>
  Effect.map(tenant, (t) => `id=${entry.request.id} tenant=${t}`)
)

// 2. make + batchN(2): which caller's Tenant does runAll see?
const runAllSaw: Array<string> = []
const batched = RequestResolver.make<Get>((entries) =>
  Effect.map(tenant, (t) => {
    runAllSaw.push(`ids=${entries.map((e) => e.request.id)} tenant=${t}`)
    for (const entry of entries) entry.completeUnsafe(Exit.succeed(t))
  })
).pipe(RequestResolver.batchN(2))

// 3. SqlResolver: execute reads the transaction and Tenant.
const sqlProbe = Effect.gen(function*() {
  const sql = yield* SqlClient.SqlClient
  const calls: Array<{ ids: ReadonlyArray<number>; inTransaction: boolean; tenant: string }> = []
  const run = SqlResolver.request(SqlResolver.void({
    Request: Schema.Number,
    execute: (ids: ReadonlyArray<number>) =>
      Effect.gen(function*() {
        const inTransaction = Option.isSome(yield* Effect.serviceOption(sql.transactionService))
        calls.push({ ids, inTransaction, tenant: yield* tenant })
        return []
      })
  }))
  yield* Effect.all([sql.withTransaction(run(1)), run(2)], { concurrency: "unbounded" })
  yield* Effect.all([
    run(3).pipe(Effect.provideService(Tenant, "acme")),
    run(4).pipe(Effect.provideService(Tenant, "globex"))
  ], { concurrency: "unbounded" })
  return calls
}).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" })))

const main = Effect.gen(function*() {
  const results = yield* Effect.all([
    Effect.request(Get({ id: 1 }), fromEffect).pipe(Effect.provideService(Tenant, "acme")),
    Effect.request(Get({ id: 2 }), fromEffect).pipe(Effect.provideService(Tenant, "globex"))
  ], { concurrency: "unbounded" })
  console.log("1 fromEffect results:", JSON.stringify(results))

  yield* Effect.all([
    Effect.request(Get({ id: 1 }), batched).pipe(Effect.provideService(Tenant, "first")),
    Effect.request(Get({ id: 2 }), batched).pipe(Effect.provideService(Tenant, "second")),
    Effect.request(Get({ id: 3 }), batched).pipe(Effect.provideService(Tenant, "third"))
  ], { concurrency: "unbounded" })
  console.log("2 batchN(2) runAll saw:", JSON.stringify(runAllSaw))

  console.log("3 SqlResolver execute calls:", JSON.stringify(yield* sqlProbe))
})

Effect.runPromise(main)

Output:

1 fromEffect results: ["id=1 tenant=acme","id=2 tenant=acme"]
2 batchN(2) runAll saw: ["ids=1,2 tenant=second","ids=3 tenant=third"]
3 SqlResolver execute calls: [{"ids":[1],"inTransaction":true,"tenant":"none"},{"ids":[2],"inTransaction":false,"tenant":"none"},{"ids":[3,4],"inTransaction":false,"tenant":"acme"}]

Line 1 shows that request 2 read acme, the tenant of request 1. Line 2 shows that the batch of requests 1 and 2 ran with the tenant of the second caller. Line 3 shows that requests 3 and 4 ran together with the tenant acme.

Expected

  • Each fromEffect entry runs with the context of its own caller. In the reproduction, request 2 reads globex.
  • A resolver built with make always gets the context of the same caller, whether collectWhile ended the batch or not. In the reproduction, the batch of requests 1 and 2 reads the Tenant of the same caller every time.
  • SqlResolver puts callers with different services into separate batches. If it does not, the documentation says that execute sees only the services of the first caller. In the reproduction, request 4 runs with globex.

Cause

fromEffect (packages/effect/src/RequestResolver.ts:444) is built on make, so all pending entries go into one batch. It forks each f(entry) from the batch fiber (:454):

const fiber = effect.forkUnsafe(parent as any, f(entry), true)

forkUnsafe (packages/effect/src/internal/effect.ts:5539) gives the child fiber the context of the parent (:5548). Each Request.Entry has the context of its own caller (packages/effect/src/internal/request.ts:131), but fromEffect never provides this context to f(entry).

The context of the batch fiber comes from addEntry in internal/request.ts. The caller that creates a batch forks the batch fiber with its own context (:203). If collectWhile then returns false (:209), addEntry interrupts this fiber. Then it forks a new one with the context of the caller that just joined (:212). This is why, with batchN(2), requests 1 and 2 run with second, and request 3 runs with third.

SqlResolver creates its resolvers with RequestResolver.makeGrouped and groups them by transactionKey (packages/effect/src/sql/SqlResolver.ts:409). This key is the transaction connection of the caller. Each resolver then provides entries[0].context to execute, for example in SqlResolver.void (:315) and SqlResolver.ordered (:133). So the transaction is correct for every entry in a group, but all other services come from the first entry.

makeGrouped (RequestResolver.ts:302) uses its key as the batchKey of the resolver. So each group gets its own batch fiber, with the context of the first caller in that group. The callers in a group have the same values for every service that the key compares. All other services come from the first caller. We tested this with two groups, each keyed by one service. Each group ran with the Tenant of its own first caller: group=x ids=1,3 tenant=t1 and group=y ids=2,4 tenant=t2.

What RequestResolver does not have is a key that says which differences in the context matter. So every resolver that needs the context of each caller builds this key itself:

  • SqlResolver does it for transactions.
  • GraphQLResolver does it in makeResolver (packages/effect/src/graphql/GraphQLResolver.ts:636). It groups by URL and by a user batchKey, and runs each group with entries[0].context (:666).
  • The EmbeddingModel fix in Fix EmbeddingModel.embed batching callers with different contexts #9552 does it a third time. It adds an optional batchKey to EmbeddingModel.make. The provider returns the context values that embedMany reads, and makeGrouped groups the calls by these values. Each group runs with the context of its first caller.

Who is affected

  • A fromEffect resolver whose f reads a service that is different for each caller, for example the current user, a tenant, or an auth token. Concurrent requests from two users both get the service of the first user, and there is no error. If f uses this service to choose which data to load, one caller can get the data of another caller.
  • A resolver built with make or makeGrouped that reads a service in runAll and uses batchN or another collectWhile. Which caller's service it reads depends on the order in which callers arrive. So a test can pass with one order and fail with another.
  • A SqlResolver whose execute reads any service other than the transaction. Callers outside a transaction always share one batch.
  • EmbeddingModel.make after Fix EmbeddingModel.embed batching callers with different contexts #9552. Calls with equal batchKey values share one embedMany call, and every other service comes from the first caller. As Fix EmbeddingModel.embed batching callers with different contexts #9552 documents, a per-call FetchHttpClient.RequestInit, or any service that an injected HttpClient reads, takes the value of the first caller for the whole batch.

Possible directions

  1. fromEffect runs each f(entry) with entry.context. This change only affects fromEffect. make and makeGrouped keep their current behaviour.

  2. A new public constructor next to makeGrouped groups entries by their whole context, and runs each group with the context of its first entry. SqlResolver, GraphQLResolver, and EmbeddingModel.make could all use it instead of their own code. makeGrouped already does the grouping. The difficult part is deciding which services the key compares, and how. The first version of Fix EmbeddingModel.embed batching callers with different contexts #9552 used these rules:

    • Ignore services that are different on every call and that no resolver should read as a setting. These are the parent span, the stack frame, log annotations, log spans, span annotations, span links, and Schedule.CurrentMetadata. In that version, we measured why the last one matters: without it, a failed batch of 5 callers inside Effect.retry was retried as 5 separate calls.
    • Compare all other services by reference. Then a service that the resolver author did not expect still puts callers into separate batches. One example is FetchHttpClient.RequestInit, which an injected HttpClient reads.
    • Let the resolver list the services that hold its settings, and compare these by value with Equal.equals. Then callers that create equal settings separately still share a batch.
    • Make the hash and the comparison independent of the order in which services were added, and keep the lookup time linear in the number of callers.

    This direction has a cost. Each HTTP or RPC request runs with its own Scope, so calls from two different requests no longer share a batch. This cost was not accepted for EmbeddingModel. In Fix EmbeddingModel.embed batching callers with different contexts #9552, Effect Bot replaced these rules with an explicit batchKey, for two reasons. First, the list of ignored services must follow every per-call reference that core adds. Second, batching across HTTP requests is the main use of batching. The same reasons apply to SqlResolver, because SQL resolvers handle many concurrent requests and are performance-sensitive. So if RequestResolver keeps explicit keys, services outside the key still come from the first caller, and this should at least be documented.

  3. Document which caller's context runAll sees. Also make it always the context of the caller that created the batch: when addEntry forks the batch again at :212, it keeps the context of that caller. This removes the dependency on arrival order, but fromEffect and SqlResolver keep their current behaviour.

Today, a program can avoid the fromEffect problem by providing the context itself. With RequestResolver.fromEffect((entry) => Effect.provideContext(f(entry), entry.context)), the reproduction returns acme and globex.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions