# FIXEDAUTO degree alignment can reverse CKKS comparison results

**URL:** <https://openfhe.discourse.group/t/fixedauto-degree-alignment-can-reverse-ckks-comparison-results/2403>\
**Category:** Bug Reports\
**Created:** [November 5, 2026, 8:13am UTC](https://openfhe.discourse.group/t/fixedauto-degree-alignment-can-reverse-ckks-comparison-results/2403 "2026-11-05T08:13:48Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![CCYJ](https://avatars.discourse-cdn.com/v4/letter/c/b5ac83/32.png) [@CCYJ](https://openfhe.discourse.group/u/CCYJ)\
**Post date:** [November 5, 2026, 8:13am UTC](https://openfhe.discourse.group/t/fixedauto-degree-alignment-can-reverse-ckks-comparison-results/2403/1 "2026-11-05T08:13:48Z")

</div>

## Summary

With OpenFHE `v1.6.1`, `EvalCompareSchemeSwitching` can return the opposite comparison bit when valid `FIXEDAUTO` CKKS operands have different `NoiseScaleDeg` values. The reproducer creates degree-2 ciphertexts with the public `EvalMult(ciphertext, 1.0)` operation and confirms that both operands still decrypt to their intended values. For a clear difference of `-3` or `+3`, mixed-degree `EvalSub` decrypts to about `+0.5999` or `-0.5999`; the comparison is reversed in all eight slots, in either operand order. Equal-degree controls pass, and adding encrypted `1.0` to the returned comparison ciphertext preserves all eight wrong results. A mixed-degree `d=4` comparison control passes.

## Environment

- **Library version and commit:** OpenFHE `v1.6.1`, commit `b59e1f291965f14fbee5172cd83a20f5b856204f`.
- **CKKS:** `FIXEDAUTO`, scaling bits 29, ring dimension 8192, eight slots; comparison switching uses CKKS `HEStd_NotSet` and FHEW `TOY` parameters for this functional reproducer.

## Minimal reproduction

Build OpenFHE `v1.6.1` and set `OPENFHE_INSTALL` to its installation prefix. Save the following files as `repro.cpp` and `CMakeLists.txt` in one directory.

```sh
: "${OPENFHE_INSTALL:?Set OPENFHE_INSTALL to the OpenFHE v1.6.1 installation prefix}"
cmake -S . -B build -DCMAKE_PREFIX_PATH="$OPENFHE_INSTALL"
cmake --build build --target repro -j2
env LD_LIBRARY_PATH="$OPENFHE_INSTALL/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" \
  ./build/repro

```

**`CMakeLists.txt`**

```cmake
cmake_minimum_required(VERSION 3.16)
project(openfhe_fixedauto_mixed_degree_comparison LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(OpenFHE 1.6.1 EXACT CONFIG REQUIRED)

include_directories(
    ${OpenFHE_INCLUDE}
    ${OpenFHE_INCLUDE}/third-party/include
    ${OpenFHE_INCLUDE}/core
    ${OpenFHE_INCLUDE}/pke
    ${OpenFHE_INCLUDE}/binfhe)
link_directories(${OpenFHE_LIBDIR})

add_executable(repro repro.cpp)
target_link_libraries(repro ${OpenFHE_SHARED_LIBRARIES})

```

**`repro.cpp`**

```cpp
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <string>
#include <vector>

#include "binfhecontext.h"
#include "openfhe.h"

using namespace lbcrypto;

static std::vector<double> Decode(const CryptoContext<DCRTPoly>& cc,
                                  const PrivateKey<DCRTPoly>& sk,
                                  const Ciphertext<DCRTPoly>& ct,
                                  uint32_t slots) {
    Plaintext pt;
    cc->Decrypt(sk, ct, &pt);
    pt->SetLength(slots);
    std::vector<double> out;
    for (const auto& x : pt->GetCKKSPackedValue()) out.push_back(x.real());
    return out;
}

static uint32_t Check(const std::string& label,
                      const CryptoContext<DCRTPoly>& cc,
                      const PrivateKey<DCRTPoly>& sk,
                      const Ciphertext<DCRTPoly>& lhs,
                      const Ciphertext<DCRTPoly>& rhs,
                      const std::vector<bool>& expected, uint32_t slots,
                      uint32_t expectedMismatches) {
    auto out = cc->EvalCompareSchemeSwitching(lhs, rhs, slots, slots);
    auto values = Decode(cc, sk, out, slots);
    uint32_t mismatches = 0;
    for (uint32_t i = 0; i < slots; ++i) {
        const double want = expected[i] ? 1.0 : 0.0;
        const bool bad = std::abs(values[i] - want) > 0.08;
        mismatches += bad;
        std::cout << label << "_slot=" << i << " expected=" << want
                  << " got=" << values[i] << " mismatch=" << bad << '\n';
    }
    std::cout << label << "_mismatches=" << mismatches << '\n';
    const auto outPlusOne = cc->EvalAdd(out, 1.0);
    const auto continued = Decode(cc, sk, outPlusOne, slots);
    uint32_t continuationMismatches = 0;
    for (uint32_t i = 0; i < slots; ++i) {
        const double expectedAfterAdd = (expected[i] ? 1.0 : 0.0) + 1.0;
        continuationMismatches += std::abs(continued[i] - expectedAfterAdd) > 0.08;
    }
    std::cout << label << "_post_add_mismatches=" << continuationMismatches << '\n';
    return mismatches == expectedMismatches &&
           continuationMismatches == expectedMismatches;
}

int main() {
    std::cout << std::unitbuf;
    OpenFHEParallelControls.SetNumThreads(1);
    constexpr uint32_t slots = 8;
    constexpr uint32_t scalingBits = 29;

    CCParams<CryptoContextCKKSRNS> params;
    params.SetRingDim(8192);
    params.SetMultiplicativeDepth(18);
    params.SetFirstModSize(60);
    params.SetScalingModSize(scalingBits);
    params.SetBatchSize(slots);
    params.SetScalingTechnique(FIXEDAUTO);
    params.SetSecurityLevel(HEStd_NotSet);
    params.SetKeySwitchTechnique(HYBRID);
    params.SetNumLargeDigits(3);
    auto cc = GenCryptoContext(params);
    cc->Enable(PKE);
    cc->Enable(KEYSWITCH);
    cc->Enable(LEVELEDSHE);
    cc->Enable(ADVANCEDSHE);
    cc->Enable(SCHEMESWITCH);
    auto keys = cc->KeyGen();
    cc->EvalMultKeyGen(keys.secretKey);

    SchSwchParams sw;
    sw.SetSecurityLevelCKKS(HEStd_NotSet);
    sw.SetSecurityLevelFHEW(TOY);
    sw.SetCtxtModSizeFHEWLargePrec(25);
    sw.SetNumSlotsCKKS(slots);
    sw.SetNumValues(slots);
    sw.SetUseDynamicModeFHEW(false);
    auto lweSk = cc->EvalSchemeSwitchingSetup(sw);
    auto lwe = cc->GetBinCCForSchemeSwitch();
    lwe->BTKeyGen(lweSk);
    cc->EvalSchemeSwitchingKeyGen(keys, lweSk);
    const uint32_t pLWE = (1U << 25) / (2 * lwe->GetBeta().ConvertToInt());
    cc->EvalCompareSwitchPrecompute(pLWE, 8.0, false);
    const double base = 0.45 * pLWE;
    std::cout << "scaling_bits=" << scalingBits << " pLWE=" << pLWE
              << " base=" << base << '\n';

    for (const int d : {3, 4}) {
        std::vector<double> left(slots), right(slots);
        std::vector<bool> expected(slots);
        for (uint32_t i = 0; i < slots; ++i) {
            if ((i & 1) == 0) {
                left[i] = base - d;
                right[i] = base;
                expected[i] = true;
            } else {
                left[i] = -base + d;
                right[i] = -base;
                expected[i] = false;
            }
        }
        auto ptLeft = cc->MakeCKKSPackedPlaintext(left, 1, 0, nullptr, slots);
        auto ptRight = cc->MakeCKKSPackedPlaintext(right, 1, 0, nullptr, slots);
        auto cLeft = cc->Encrypt(keys.publicKey, ptLeft);
        auto cRight = cc->Encrypt(keys.publicKey, ptRight);
        auto cLeft2 = cc->EvalMult(cLeft, 1.0);
        auto cRight2 = cc->EvalMult(cRight, 1.0);
        const auto& targetPoly = cRight2->GetElements()[0];
        const double qLast = targetPoly.GetElementAtIndex(targetPoly.GetNumOfElements() - 1)
                                 .GetModulus().ConvertToDouble();
        const auto cryptoParams = std::dynamic_pointer_cast<CryptoParametersCKKSRNS>(cc->GetCryptoParameters());
        const double deltaScale = cryptoParams->GetScalingFactorReal(cLeft->GetLevel());
        auto mixedSub = cc->EvalSub(cLeft, cRight2);
        const auto mixedSubValues = Decode(cc, keys.secretKey, mixedSub, slots);
        std::cout << "degree_alignment_q_over_delta=" << qLast / deltaScale << '\n';
        for (uint32_t i = 0; i < slots; ++i)
            std::cout << "delta=" << d << " mixed_sub_slot=" << i
                      << " expected=" << (left[i] - right[i])
                      << " got=" << mixedSubValues[i] << '\n';

        auto leftCheck = Decode(cc, keys.secretKey, cLeft, slots);
        auto rightCheck = Decode(cc, keys.secretKey, cRight, slots);
        auto left2Check = Decode(cc, keys.secretKey, cLeft2, slots);
        auto right2Check = Decode(cc, keys.secretKey, cRight2, slots);
        double inputError = 0.0;
        for (uint32_t i = 0; i < slots; ++i)
            inputError = std::max(inputError, std::max({std::abs(leftCheck[i] - left[i]),
                                                        std::abs(rightCheck[i] - right[i]),
                                                        std::abs(left2Check[i] - left[i]),
                                                        std::abs(right2Check[i] - right[i])}));
        std::cout << "delta=" << d << " input_max_error=" << inputError << '\n';
        if (inputError > 1e-3) {
            std::cerr << "input ciphertext did not decrypt within the required control tolerance\n";
            return 2;
        }

        const std::string prefix = "d" + std::to_string(d);
        if (!Check(prefix + "_same_deg1", cc, keys.secretKey, cLeft, cRight,
                   expected, slots, 0)) return 3;
        if (!Check(prefix + "_same_deg2", cc, keys.secretKey, cLeft2, cRight2,
                   expected, slots, 0)) return 4;
        const uint32_t expectedMixedMismatches = (d == 3) ? slots : 0;
        if (!Check(prefix + "_mixed_forward", cc, keys.secretKey, cLeft, cRight2,
                   expected, slots, expectedMixedMismatches)) return 5;
        std::vector<bool> reverseExpected(slots);
        for (uint32_t i = 0; i < slots; ++i) reverseExpected[i] = !expected[i];
        if (!Check(prefix + "_mixed_reverse", cc, keys.secretKey, cRight2, cLeft,
                   reverseExpected, slots, expectedMixedMismatches)) return 6;
    }
    cc->ClearStaticMapsAndVectors();
    return 0;
}

```

## Expected behavior

For every slot, `EvalCompareSchemeSwitching(lhs, rhs, ...)` should return the comparison of the decrypted CKKS values. In the `d=3` case, the expected flags alternate `true, false`; reversing the operands should return `false, true`. Adding `1.0` to each output should preserve the expected comparison value plus one. Same-level degree-1 and degree-2 cases should agree with the mixed-degree case.

## Actual behavior

The reproducer reports `pLWE=131072`, `base=58982.4`, and `q_last/Delta=1.00006`. Both original degree-1 inputs and their degree-2 `EvalMult(ct, 1.0)` forms decrypt within `6.2e-6` of the encoded values. For `d=3`, direct subtraction returns about `+0.5999` where the expected value is `-3`, and about `-0.5999` where the expected value is `+3`. Both mixed-degree argument orders produce 8/8 wrong comparison slots, and their encrypted `+1` continuations also have 8/8 wrong slots. The degree-1 and degree-2 homogeneous controls have no wrong slots. With `d=4`, the mixed-degree comparisons and continuations pass.

A separate public-API sweep exercised the different-level alignment branch with a level-0 degree-1 operand and level-1 through level-8 degree-2 operands. Direct subtraction was wrong in all slots at every level gap; comparison bits reversed in all slots at odd gaps and passed at even gaps. The source ciphertexts in that sweep decrypted within `7.7e-6` of their inputs.

## Impact

Valid `FIXEDAUTO` ciphertexts with different `NoiseScaleDeg` values can produce an incorrect CKKS difference before scheme switching. `EvalCompareSchemeSwitching` can consequently return every comparison bit reversed, and subsequent CKKS computation on its output preserves the wrong bit. The failure appears for inputs close enough to the comparison boundary that the alignment error crosses zero; same-degree controls and a slightly larger difference pass.

## Cause analysis

`EvalSub` aligns the operands before subtracting. In the mixed-degree `FIXEDAUTO` branch, OpenFHE raises the lower-degree polynomial by multiplying it by the target’s last Q modulus `q_last`, but updates its scale metadata using `Delta`. No rescale removes the resulting `q_last / Delta` factor before subtraction. Here that ratio is `1.00006`; at an input magnitude near `58,982`, the residual changes the difference by about `3.6`, enough to turn `-3` into approximately `+0.6` and `+3` into approximately `-0.6`. `EvalCompareSchemeSwitching` feeds this incorrect difference to CKKS-to-FHEW conversion and FHEW sign evaluation.

The level-gap sweep reaches the separate `c1lvl != c2lvl`, `c1depth != c2depth` branch of the same alignment routine and shows the same failure pattern. At odd gaps `q_last/Delta < 1` reverses the near-zero comparison; at even gaps it changes the subtraction value but does not cross zero for this input.

## Relevant source locations

- [OpenFHE v1.6.1 `AdjustLevelsAndDepthInPlace` degree alignment](https://github.com/openfheorg/openfhe-development/blob/b59e1f291965f14fbee5172cd83a20f5b856204f/src/pke/lib/scheme/ckksrns/ckksrns-leveledshe.cpp#L664-L722)
- [OpenFHE v1.6.1 `EvalSubInPlace` calling operand alignment before subtraction](https://github.com/openfheorg/openfhe-development/blob/b59e1f291965f14fbee5172cd83a20f5b856204f/src/pke/lib/schemerns/rns-leveledshe.cpp#L145-L160)
- [OpenFHE v1.6.1 addition/subtraction adjustment dispatch](https://github.com/openfheorg/openfhe-development/blob/b59e1f291965f14fbee5172cd83a20f5b856204f/src/pke/lib/schemerns/rns-leveledshe.cpp#L437-L513)
- [OpenFHE v1.6.1 comparison scheme-switching path](https://github.com/openfheorg/openfhe-development/blob/b59e1f291965f14fbee5172cd83a20f5b856204f/src/pke/lib/scheme/ckksrns/ckksrns-schemeswitching.cpp#L1357-L1388)
- [OpenFHE v1.6.1 public comparison declaration](https://github.com/openfheorg/openfhe-development/blob/b59e1f291965f14fbee5172cd83a20f5b856204f/src/pke/include/cryptocontext.h#L4207-L4240)

## Suggested direction

Make the polynomial adjustment and scale metadata describe the same effective scale, or otherwise compensate for the residual `q_last/Delta` factor before subtraction.
