[flagd] fractional shorthand buckets an empty targetingKey instead of falling back to the default variant

Abierto Apto para principiantes
#1,991 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 2 días

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
78/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
java
Área
tooling

Línea de trabajo

La comprobación de la forma abreviada está en tools/flagd-core/src/main/java/dev/openfeature/contrib/tools/flagd/core/targeting/Fractional.java, en las comprobaciones getTargetingKey() == null cerca de las líneas 57 y 72; FlagProperties en Operator.java conserva las cadenas vacías. Lee la corrección en Go de open-feature/flagd#1949 para conocer el comportamiento previsto. Está terminado cuando un targetingKey vacío devuelve la variante por defecto en ambas ramas de la forma abreviada y un caso de FractionalTest lo cubre, mientras que las claves con nombre siguen conservando sus variantes.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

open-feature/flagd#1948 compared how the SDKs handle a null, missing or empty targeting key in the fractional shorthand, and its suggested fix reads: "In all 3 cases (targeting key is null/nil, missing, or ""), we want to return null and fall back to the default variant." The Java flagd-core still hashes "". For a 10% rollout named new-checkout, the "" bucket happens to fall inside the 10%, so every empty-key request gets on from a Java service that evaluates in process and off from a Go, JS, Python or .NET one, or from the same Java service in RPC mode, where flagd itself rejects the empty key.

Fractional.java#L57 and #L72 only check getTargetingKey() == null, and FlagProperties keeps any string, so an empty key is hashed as [flagKey, ""]. Go implemented the fix in open-feature/flagd#1949 (fractional.go#L173-L175, tested as "empty targetingKey returns default variant" in fractional_test.go#L486).

Environment: dev.openfeature.contrib.providers:flagd 0.15.0 with dev.openfeature.contrib.tools:flagd-core 3.0.0 (the latest releases of both), dev.openfeature:sdk 1.23.0, Java 21.0.13.1, Ubuntu 24.04 x86_64. main at 4f4742d has the same Fractional.java and Operator.java. The RPC comparison used flagd v0.19.0 (ghcr.io/open-feature/flagd:v0.19.0).

Reproduction

flags.json holds the testbed's fractional-flag-shorthand flag and a 10% rollout:

{
  "flags": {
    "fractional-flag-shorthand": {
      "state": "ENABLED",
      "variants": { "heads": "heads", "tails": "tails", "draw": "draw" },
      "defaultVariant": "draw",
      "targeting": { "fractional": [["heads"], ["tails", 1]] }
    },
    "new-checkout": {
      "state": "ENABLED",
      "variants": { "on": "on", "off": "off" },
      "defaultVariant": "off",
      "targeting": { "fractional": [["on", 10], ["off", 90]] }
    }
  }
}

Main.java, with dev.openfeature.contrib.providers:flagd:0.15.0 and dev.openfeature:sdk:1.23.0 on the classpath:

package repro;

import dev.openfeature.contrib.providers.flagd.Config;
import dev.openfeature.contrib.providers.flagd.FlagdOptions;
import dev.openfeature.contrib.providers.flagd.FlagdProvider;
import dev.openfeature.sdk.Client;
import dev.openfeature.sdk.EvaluationContext;
import dev.openfeature.sdk.FlagEvaluationDetails;
import dev.openfeature.sdk.ImmutableContext;
import dev.openfeature.sdk.OpenFeatureAPI;

public class Main {
    public static void main(String[] args) throws Exception {
        OpenFeatureAPI api = OpenFeatureAPI.getInstance();
        api.setProviderAndWait(new FlagdProvider(FlagdOptions.builder()
                .resolverType(Config.Resolver.FILE)
                .offlineFlagSourcePath("flags.json")
                .build()));
        Client client = api.getClient();
        for (String flag : new String[] {"fractional-flag-shorthand", "new-checkout"}) {
            for (String tk : new String[] {"user-1", "user-2", "", null}) {
                EvaluationContext ctx = tk == null ? new ImmutableContext() : new ImmutableContext(tk);
                FlagEvaluationDetails<String> d = client.getStringDetails(flag, "code-default", ctx);
                System.out.printf("%-26s targetingKey=%-8s value=%s reason=%s%n", flag,
                        tk == null ? "(none)" : "\"" + tk + "\"", d.getValue(), d.getReason());
            }
        }
        api.shutdown();
    }
}

Expected

An empty key behaves like a missing one, as it does for the same flags.json in flagd's Go core v0.19.3, @openfeature/flagd-core 5.0.0, openfeature-flagd-core 2.0.0, OpenFeature.Providers.Flagd.Core 2.0.3 and this provider with Config.Resolver.RPC against flagd v0.19.0:

fractional-flag-shorthand  targetingKey=""       value=draw reason=DEFAULT
new-checkout               targetingKey=""       value=off reason=DEFAULT

What happens instead

fractional-flag-shorthand  targetingKey="user-1" value=heads reason=TARGETING_MATCH
fractional-flag-shorthand  targetingKey="user-2" value=tails reason=TARGETING_MATCH
fractional-flag-shorthand  targetingKey=""       value=tails reason=TARGETING_MATCH
fractional-flag-shorthand  targetingKey=(none)   value=draw reason=DEFAULT
new-checkout               targetingKey="user-1" value=off reason=TARGETING_MATCH
new-checkout               targetingKey="user-2" value=on reason=TARGETING_MATCH
new-checkout               targetingKey=""       value=on reason=TARGETING_MATCH
new-checkout               targetingKey=(none)   value=off reason=DEFAULT

FlagdCore from flagd-core 3.0.0 called directly and the IN_PROCESS resolver syncing from flagd v0.19.0 give the same results. The SDK keeps "" as a targeting key on purpose (open-feature/java-sdk#1807).

Possible fix

Treat an empty key like a missing one in both shorthand branches of Fractional.evaluate (L57 and L72):

-            if (properties.getTargetingKey() == null) {
+            if (properties.getTargetingKey() == null || properties.getTargetingKey().isEmpty()) {

With this change on the 3.0.0 tag, the program prints value=draw reason=DEFAULT and value=off reason=DEFAULT for the empty key, and 100,000 named keys (user-0 to user-99999) keep their variants for both flags. I can open a PR with this and a test in FractionalTest.

Notes

  • .NET changed in open-feature/dotnet-sdk-contrib#635, and its Java counterpart, #1778, kept the == null check. I searched issues and PRs here for empty targeting key, fractional and 1948, and in flagd and flagd-testbed for empty targeting key; none tracks the Java change.
  • The fractional spec (fractional-operation-spec.md#L18) and its ADR don't mention the empty string, and step 3 of the ADR says "if targetingKey is a string" (fractional-non-string-rand-units.md#L93-L95), but the ADR's Go implementation (open-feature/flagd#2011) lists "an implicit targetingKey is missing, non-string, or empty" as an error. A sentence in the spec and an empty-key row in the testbed's "Fractional operator invalid implicit inputs" outline (targeting.feature#L750-L761) would cover every provider.
  • Whitespace-only keys are a separate difference: only .NET returns the default for " ".
  • This only concerns the shorthand. The testbed expects an explicit empty hashing_input to resolve to bucket4 (targeting.feature#L703-L711).

Checking the empty-key rule with Haze

I modeled the shorthand's key check in Haze. The complete model evaluates new-checkout for a named user (bucket uniform on 0..99), an empty key (bucket 3, the real bucket of ["new-checkout", ""]) or a missing key, with the current check and with the proposed one.

def java_rejects(k : Key) : Bool := k == Missing
def spec_rejects(k : Key) : Bool := k == Missing or k == Empty

def outcome(fix : Bool) : Outcome :=
  if (if fix then spec_rejects(key) else java_rejects(key)) then Default
  else if (if key == Empty then empty_bucket else user_bucket) < 10 then On
  else Off

theorem empty_key_falls_back : outcome(false) == Default given key == Empty
theorem missing_key_falls_back : outcome(false) == Default given key == Missing
theorem empty_key_falls_back_fixed : outcome(true) == Default given key == Empty
theorem named_users_unchanged : key == Named implies outcome(false) == outcome(true)
Check Result
Empty key falls back to the default (current check) Rejected: probability 0, counterexample key = Empty
Missing key falls back to the default (current check) Accepted
Empty key falls back to the default (with the fix) Accepted
Named users get the same outcome with the fix Accepted
Empty-key requests that get on: current / fixed 1 / 0
Named-user requests that get on: current / fixed 0.1 / 0.1

The counterexample key = Empty is the new-checkout targetingKey="" value=on line above, and the fixed variant agrees with the patched run. The model replaces the 32-bit hash with 100 buckets and takes the empty key's bucket from the real hash, so its numbers describe this one flag. They are model results, not rates from production traffic.

Run the Haze model and compare its output

The model, checker and recorded output are pinned to Haze commit b34b9e77. With elan installed, these commands build and run that revision in a Unix shell:

git clone https://github.com/ritabratamaiti/haze-lang
cd haze-lang
git checkout --detach b34b9e77f3bd0865243520c997eb42b6623e8694
lake build haze
.lake/build/bin/haze examples/Found/openfeature_java.hz

Exit status 1 is expected: the file deliberately includes rejected claims. The comparison variants and full diagnostics are in the same file.

Lenguaje dominante
Java
Estrellas
51
Forks
90
Merge medio
1 d 6 h
PR fusionados (30 d)
14

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de open-feature/java-sdk-contrib

Todos los issues de open-feature/java-sdk-contrib

Issues similares

Más issues de Java

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.