{"record":{"id":"c6ac5c271e249e7c","repo":"twigphp/Twig","slug":"failed-to-load-twig-template-s-index-s-cache-might-be","errorCode":null,"errorMessage":"Failed to load Twig template \"%s\", index \"%s\": cache might be corrupted.","messagePattern":"Failed to load Twig template \"(.+?)\", index \"(.+?)\": cache might be corrupted\\.","errorType":"exception","errorClass":"Twig\\Error\\RuntimeError","httpStatus":null,"severity":"error","filePath":"src/Environment.php","lineNumber":424,"sourceCode":"            if (!class_exists($cls, false)) {\n                $source = $this->getLoader()->getSourceContext($name);\n                $content = $this->compileSource($source);\n                if (!isset($this->hotCache[$name])) {\n                    $this->cache->write($key, $content);\n                    $this->cache->load($key);\n                }\n\n                if (!class_exists($mainCls, false)) {\n                    /* Last line of defense if either $this->bcWriteCacheFile was used,\n                     * $this->cache is implemented as a no-op or we have a race condition\n                     * where the cache was cleared between the above calls to write to and load from\n                     * the cache.\n                     */\n                    eval('?>'.$content);\n                }\n\n                if (!class_exists($cls, false)) {\n                    throw new RuntimeError(\\sprintf('Failed to load Twig template \"%s\", index \"%s\": cache might be corrupted.', $name, $index), -1, $source);\n                }\n            }\n        }\n\n        $this->extensionSet->initRuntime();\n\n        return $this->loadedTemplates[$cls] = new $cls($this);\n    }\n\n    /**\n     * Creates a template from source.\n     *\n     * This method should not be used as a generic way to load templates.\n     *\n     * @param string      $template The template source\n     * @param string|null $name     An optional name of the template to be used in error messages\n     *\n     * @throws LoaderError When the template cannot be found","sourceCodeStart":406,"sourceCodeEnd":442,"githubUrl":"https://github.com/twigphp/Twig/blob/a414c3a491defb5a60f2fc88ef79ff37c90010cd/src/Environment.php#L406-L442","documentation":"Environment::loadTemplate throws this Twig\\RuntimeError after writing/reading the compiled template cache class: the eval'd compiled code did not define the expected template class ($cls). Twig treats this as evidence the on-disk compiled cache is stale, truncated, or corrupted (e.g. same cache file reused across incompatible Twig versions).","triggerScenarios":"loadTemplate() compiled a template whose cache file already existed, eval'd it, but class_exists($cls, false) was still false. Typically: stale cache dir left by an older Twig major version, truncated cache file (disk full, concurrent write without locking), an opcode/caching layer swallowing the eval, or a custom CacheInterface writing broken PHP.","commonSituations":"Deploying a Twig upgrade without clearing var/cache or templates_c; multiple PHP-FPM workers racing on the same cache file; disk-full cutting the cache write short; vendor caches baked into container images with a different Twig version than runtime.","solutions":["Delete the compiled template cache directory (e.g. var/cache/* or templates_c) and let Twig regenerate it.","Ensure cache dir permissions are writable by the PHP user and that disk has space.","Check that only one Twig major version is installed (composer why twig/twig) and that app cache was invalidated on upgrade.","If concurrency is suspected, use per-process cache dirs or a locking cache implementation (Twig\\Cache\\FilesystemCache with proper atomic writes).","If a custom cache/loader extension was written, verify the generated class name matches the one Twig expects."],"exampleFix":"// before (deploy script leaves stale cache)\nrsync -a new-code/ /var/www/app/\n\n// after\nrsync -a new-code/ /var/www/app/\nrm -rf /var/www/app/var/cache/*","handlingStrategy":"try-catch","validationCode":"// before rendering in production deploy scripts:\n$cacheDir = $config['cache'];\nforeach (glob($cacheDir.'/*', GLOB_ONLYDIR) as $d) { /* ensure writable */ }\nif (!is_writable($cacheDir)) { throw new RuntimeException('Twig cache dir not writable: '.$cacheDir); }\n// on deploy: clear cache\narray_map('unlink', glob($cacheDir.'/*/*.php'));","typeGuard":null,"tryCatchPattern":"try {\n    $html = $twig->render('index.html.twig', $ctx);\n} catch (\\Twig\\Error\\RuntimeError $e) {\n    if (str_contains($e->getMessage(), 'cache might be corrupted')) {\n        foreach (new \\RecursiveIteratorIterator(new \\RecursiveDirectoryIterator($cacheDir, \\FilesystemIterator::SKIP_DOTS)) as $f) { @unlink($f); }\n        $html = $twig->render('index.html.twig', $ctx);\n    } else { throw $e; }\n}","preventionTips":["Always clear the compiled-template cache when upgrading twig/twig or deploying code that changes templates.","Monitor disk space and file-write failures on the cache volume.","Use atomic cache writes (write to temp file then rename) if multiple workers share the cache dir.","Pin one Twig major version in composer.json and run composer why twig/twig in CI."],"tags":["twig","template-cache","runtime-error"],"backgroundTag":"cache-corruption","analyzedSha":"a414c3a491defb5a60f2fc88ef79ff37c90010cd","analyzedAt":"2026-09-13T15:10:46.849Z","contentChangedAt":"2026-09-13T15:10:46.849Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}