graphql-java / graphql-java/java-dataloader

[Bug] Memory Leak and Stats Pollution via unmanaged ThreadLocal in ThreadLocalStatisticsCollector

Abierto
#266 1 comentario 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

keep-open
Lenguaje dominante
Java
Estrellas
525
Forks
101
Métricas de merge de PR
Sin PR fusionados en 30 d

Descripción

Describe the bug
There is a potential Unintentional ThreadLocal Leak (UTL) in ThreadLocalStatisticsCollector. The class relies on consumers manually calling resetThread() at "request boundaries" to clear the ThreadLocal<SimpleStatisticsCollector>.

However, in typical GraphQL environments (reactive streams, async gateways, or standard thread pools), threads are heavily reused. If an unhandled exception occurs or a developer forgets to call resetThread(), the SimpleStatisticsCollector object is permanently retained by the worker thread.

Impact:

  1. Data Pollution: Subsequent requests processed by the dirty thread will inherit the accumulated statistics of previous requests, leading to completely distorted metrics.
  2. Memory Leak (Type I UTL): As more threads in the pool retain these un-cleared statistics objects over time, the heap usage will grow linearly, potentially leading to an OutOfMemoryError in high-throughput applications.

To Reproduce
Here is a simplified code example demonstrating the data pollution in a thread-pool environment when resetThread() is missed (e.g., bypassed due to an exception):

import org.dataloader.stats.ThreadLocalStatisticsCollector;
import java.util.concurrent.*;

public class UTLReproduction {
    public static void main(String[] args) throws Exception {
        ThreadLocalStatisticsCollector collector = new ThreadLocalStatisticsCollector();
        // Simulate a web server with a reusable thread pool
        ExecutorService threadPool = Executors.newFixedThreadPool(1);

        // Request 1: Execution completes but resetThread() is missed (e.g. exception thrown)
        threadPool.submit(() -> {
            collector.incrementLoadCount();
            // Developer forgets to put collector.resetThread() in a finally block
        }).get();

        // Request 2: A new incoming request reuses the same dirty thread
        threadPool.submit(() -> {
            long loadCount = collector.getStatistics().getLoadCount();
            // BUG: loadCount is 1 instead of 0! The new request is polluted by Request 1.
            System.out.println("New Request Load Count (Expected 0): " + loadCount);
        }).get();
        
        threadPool.shutdown();
    }
}

Guía de contribución

No hay ninguna guía de contribución indexada para este repositorio

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.

Línea de trabajo

Empieza leyendo ThreadLocalStatisticsCollector, especialmente su uso de ThreadLocal, getStatistics() y resetThread(). Ejecuta la reproducción proporcionada con un fixed-thread-pool para verificar si las estadísticas persisten entre requests cuando se omite resetThread(). Done debe incluir una forma decidida de evitar la contaminación y retención entre requests, con tests que cubran el escenario reproducido.

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

Evaluación

Stack tecnológico
java
Área
backend, observability
Tipo de issue
Error
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Tranquilo
Claridad
Necesita aclaración
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.