DEBUG.WIKI
PanstarCloud:部署应用,接入 AI,云服务器与 AI 网关
晚安云;香港 CN2 ¥15/月
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS

解决 Apollo Federation 报错 Composition failed subgraph 合图失败修复

排查 Apollo Federation 2 使用 Rover CLI 或 Apollo Studio 执行超级图合成(Supergraph Composition)时报错 Composition failed: Incompatible type definitions across subgraphs,分析 子图命名冲突与 @key/@shareable 声明缺失。

问题现象

在 CI/CD 流水线中构建 Apollo Federation Supergraph 时,构建脚本抛出模式合成失败:

error[E029]: [users-subgraph] Field "User.email" is defined in multiple subgraphs without being marked @shareable.
error[E015]: [products-subgraph] Key directive specifies field "id" which does not exist in type "Product".

触发根因

  1. Federation 2 规范严格要求:如果同一个类型(如 User)的同一个字段(如 email)在多个独立的子图中重复定义,必须显式标注 @shareable 指令;
  2. 实体类型上的 @key 指令引用的主键字段在子图内部未声明为本实体字段;
  3. 不同子图之间同名自定义标量(Scalar)或输入类型的结构定义产生了冲突。

解决步骤

在多子图共享字段上显式追加 @shareable 指令

更新子图 GraphQL Schema:

extend schema @link(url: "https://specs.apollo.dev/federation/v2.3", import: ["@key", "@shareable"])

type User @key(fields: "id") {
  id: ID!
  email: String! @shareable
}

使用 Rover CLI 在本地快速复现并验证合成结果

执行本地合成命令:

rover supergraph compose --config ./supergraph.yaml > supergraph.graphql

将共享通用类型(如 PageInfo)统一定义在独立的核心共享子图中

保持架构边界清晰。

验证确认

重新触发合成构建:

Rover 顺利输出 Composed successfully,生成干净的 supergraph.graphql,网关平滑接纳双向路由。