cubicweb #1520527 Wrong sql generated by EXISTS clause [resolved]

To reproduce, use the pagode schema (private repo)

The following RQL:

DISTINCT Any O
WHERE O is Scenario,
      EXISTS(S is RunExecution,
             S eid 4111,
             S in_case C,
             N rcase_of C,
             N inflow TSB,
             TSB ts_variant TSV,
             TSV has_scenario O)

generates the following SQL:

SELECT DISTINCT _TSV.cw_has_scenario
WHERE EXISTS
(SELECT 1
 FROM cw_RunExecution AS _S, cw_Node AS _N, ts_variant_relation AS rel_ts_variant0, cw_TimeSeries AS _TSV
 WHERE _S.cw_eid=%(207771324)s
  AND _S.cw_in_case IS NOT NULL
  AND _N.cw_rcase_of=_S.cw_in_case AND _N.cw_inflow IS NOT NULL
  AND _N.cw_inflow=rel_ts_variant0.eid_from AND rel_ts_variant0.eid_to=_TSV.cw_eid
  AND _TSV.cw_has_scenario IS NOT NULL
UNION
 SELECT 1
 FROM cw_Turbine AS _N, ts_variant_relation AS rel_ts_variant1
 WHERE _S.cw_eid=%(207771324)s
  AND _S.cw_in_case IS NOT NULL
  AND _N.cw_rcase_of=_S.cw_in_case
  AND _N.cw_inflow IS NOT NULL
  AND _N.cw_inflow=rel_ts_variant1.eid_from
  AND rel_ts_variant1.eid_to=_TSV.cw_eid
  AND _TSV.cw_has_scenario IS NOT NULL
UNION
 SELECT 1
  FROM cw_Reservoir AS _N, ts_variant_relation AS rel_ts_variant2
 WHERE _S.cw_eid=%(207771324)s
  AND _S.cw_in_case IS NOT NULL
  AND _N.cw_rcase_of=_S.cw_in_case
  AND _N.cw_inflow IS NOT
  NULL AND _N.cw_inflow=rel_ts_variant2.eid_from
  AND rel_ts_variant2.eid_to=_TSV.cw_eid
  AND _TSV.cw_has_scenario IS NOT NULL)

and Postgresql complains that:

ProgrammingError: ERREUR:  entrée manquante de la clause FROM pour la table « _tsv »
LINE 1: SELECT DISTINCT _TSV.cw_has_scenario
                        ^
prioritynormal
typebug
done in3.12.1
load0.300
load left0.000
closed by<not specified>