yql_aggregate_expander.cpp 122 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977
  1. #include "yql_aggregate_expander.h"
  2. #include <yql/essentials/core/yql_expr_optimize.h>
  3. #include <yql/essentials/core/yql_expr_type_annotation.h>
  4. #include <yql/essentials/core/yql_opt_window.h>
  5. #include <yql/essentials/core/yql_opt_utils.h>
  6. #include <yql/essentials/core/yql_type_helpers.h>
  7. #include <yql/essentials/utils/log/log.h>
  8. namespace NYql {
  9. TExprNode::TPtr TAggregateExpander::ExpandAggregate() {
  10. YQL_CLOG(DEBUG, Core) << "Expand " << Node->Content();
  11. auto result = ExpandAggregateWithFullOutput();
  12. if (result) {
  13. auto outputColumns = GetSetting(*Node->Child(NNodes::TCoAggregate::idx_Settings), "output_columns");
  14. if (outputColumns) {
  15. result = Ctx.NewCallable(result->Pos(), "ExtractMembers", { result, outputColumns->ChildPtr(1) });
  16. }
  17. }
  18. return result;
  19. }
  20. TExprNode::TPtr TAggregateExpander::ExpandAggregateWithFullOutput()
  21. {
  22. Suffix = Node->Content();
  23. YQL_ENSURE(Suffix.SkipPrefix("Aggregate"));
  24. AggList = Node->HeadPtr();
  25. KeyColumns = Node->ChildPtr(1);
  26. AggregatedColumns = Node->Child(2);
  27. auto settings = Node->Child(3);
  28. bool allTraitsCollected = CollectTraits();
  29. YQL_ENSURE(!HasSetting(*settings, "hopping"), "Aggregate with hopping unsupported here.");
  30. HaveDistinct = AnyOf(AggregatedColumns->ChildrenList(),
  31. [](const auto& child) { return child->ChildrenSize() == 3; });
  32. EffectiveCompact = (HaveDistinct && CompactForDistinct && !UseBlocks) || ForceCompact || HasSetting(*settings, "compact");
  33. for (const auto& trait : Traits) {
  34. auto mergeLambda = trait->Child(5);
  35. if (mergeLambda->Tail().IsCallable("Void")) {
  36. EffectiveCompact = true;
  37. break;
  38. }
  39. }
  40. if (Suffix == "Finalize") {
  41. EffectiveCompact = true;
  42. Suffix = "";
  43. } else if (Suffix != "") {
  44. EffectiveCompact = false;
  45. }
  46. OriginalRowType = GetSeqItemType(*Node->Head().GetTypeAnn()).Cast<TStructExprType>();
  47. RowItems = OriginalRowType->GetItems();
  48. ProcessSessionSetting(GetSetting(*settings, "session"));
  49. RowType = Ctx.MakeType<TStructExprType>(RowItems);
  50. TVector<const TTypeAnnotationNode*> keyItemTypes = GetKeyItemTypes();
  51. bool needPickle = IsNeedPickle(keyItemTypes);
  52. auto keyExtractor = GetKeyExtractor(needPickle);
  53. CollectColumnsSpecs();
  54. if (Suffix == "" && !HaveSessionSetting && !EffectiveCompact && UsePhases) {
  55. return GeneratePhases();
  56. }
  57. if (UseBlocks) {
  58. if (Suffix == "Combine") {
  59. auto ret = TryGenerateBlockCombine();
  60. if (ret) {
  61. return ret;
  62. }
  63. }
  64. if (Suffix == "MergeFinalize" || Suffix == "MergeManyFinalize") {
  65. auto ret = TryGenerateBlockMergeFinalize();
  66. if (ret) {
  67. return ret;
  68. }
  69. }
  70. }
  71. if (!allTraitsCollected) {
  72. return RebuildAggregate();
  73. }
  74. BuildNothingStates();
  75. if (Suffix == "MergeState" || Suffix == "MergeFinalize" || Suffix == "MergeManyFinalize") {
  76. return GeneratePostAggregate(AggList, keyExtractor);
  77. }
  78. TExprNode::TPtr preAgg = GeneratePartialAggregate(keyExtractor, keyItemTypes, needPickle);
  79. if (EffectiveCompact || !preAgg) {
  80. preAgg = std::move(AggList);
  81. }
  82. if (Suffix == "Combine" || Suffix == "CombineState") {
  83. return preAgg;
  84. }
  85. return GeneratePostAggregate(preAgg, keyExtractor);
  86. }
  87. TExprNode::TPtr TAggregateExpander::ExpandAggApply(const TExprNode::TPtr& node)
  88. {
  89. auto name = node->Head().Content();
  90. if (name.StartsWith("pg_")) {
  91. auto func = name.SubStr(3);
  92. auto itemType = node->Child(1)->GetTypeAnn()->Cast<TTypeExprType>()->GetType();
  93. TVector<ui32> argTypes;
  94. bool needRetype = false;
  95. auto status = ExtractPgTypesFromMultiLambda(node->ChildRef(2), argTypes, needRetype, Ctx);
  96. YQL_ENSURE(status == IGraphTransformer::TStatus::Ok);
  97. const NPg::TAggregateDesc* aggDescPtr;
  98. if (node->Content().EndsWith("State")) {
  99. auto stateType = node->Child(2)->GetTypeAnn()->Cast<TPgExprType>()->GetId();
  100. auto resultType = node->GetTypeAnn()->Cast<TPgExprType>()->GetId();
  101. aggDescPtr = &NPg::LookupAggregation(TString(func), stateType, resultType);
  102. } else {
  103. aggDescPtr = &NPg::LookupAggregation(TString(func), argTypes);
  104. }
  105. return ExpandPgAggregationTraits(node->Pos(), *aggDescPtr, false, node->ChildPtr(2), argTypes, itemType, Ctx);
  106. }
  107. const TString modulePath = "/lib/yql/aggregate.yqls";
  108. auto exportsPtr = TypesCtx.Modules->GetModule(modulePath);
  109. YQL_ENSURE(exportsPtr, "Failed to get module " << modulePath);
  110. const auto& exports = exportsPtr->Symbols();
  111. const auto ex = exports.find(TString(name) + "_traits_factory");
  112. YQL_ENSURE(exports.cend() != ex);
  113. TNodeOnNodeOwnedMap deepClones;
  114. auto lambda = Ctx.DeepCopy(*ex->second, exportsPtr->ExprCtx(), deepClones, true, false);
  115. auto listTypeNode = Ctx.NewCallable(node->Pos(), "ListType", { node->ChildPtr(node->ChildrenSize() == 4 && !node->Child(3)->IsCallable("Void") ? 3 : 1) });
  116. auto extractor = node->ChildPtr(2);
  117. auto traits = Ctx.ReplaceNodes(lambda->TailPtr(), {
  118. {lambda->Head().Child(0), listTypeNode},
  119. {lambda->Head().Child(1), extractor}
  120. });
  121. Ctx.Step.Repeat(TExprStep::ExpandApplyForLambdas);
  122. auto status = ExpandApplyNoRepeat(traits, traits, Ctx);
  123. YQL_ENSURE(status != IGraphTransformer::TStatus::Error);
  124. return traits;
  125. }
  126. bool TAggregateExpander::CollectTraits() {
  127. bool allTraitsCollected = true;
  128. for (ui32 index = 0; index < AggregatedColumns->ChildrenSize(); ++index) {
  129. auto trait = AggregatedColumns->Child(index)->ChildPtr(1);
  130. if (trait->IsCallable({ "AggApply", "AggApplyState", "AggApplyManyState" })) {
  131. trait = ExpandAggApply(trait);
  132. allTraitsCollected = false;
  133. }
  134. Traits.push_back(trait);
  135. }
  136. return allTraitsCollected;
  137. }
  138. TExprNode::TPtr TAggregateExpander::RebuildAggregate()
  139. {
  140. TExprNode::TListType newAggregatedColumnsItems = AggregatedColumns->ChildrenList();
  141. for (ui32 index = 0; index < AggregatedColumns->ChildrenSize(); ++index) {
  142. auto trait = AggregatedColumns->Child(index)->ChildPtr(1);
  143. if (trait->IsCallable("AggApply")) {
  144. newAggregatedColumnsItems[index] = Ctx.ChangeChild(*(newAggregatedColumnsItems[index]), 1, std::move(Traits[index]));
  145. } else if (trait->IsCallable("AggApplyState") || trait->IsCallable("AggApplyManyState")) {
  146. auto newTrait = Ctx.Builder(Node->Pos())
  147. .Callable("AggregationTraits")
  148. .Add(0, trait->ChildPtr(1))
  149. .Add(1, trait->ChildPtr(2)) // extractor for state, not initial value itself
  150. .Lambda(2)
  151. .Param("item")
  152. .Param("state")
  153. .Callable("Void")
  154. .Seal()
  155. .Seal()
  156. .Add(3, Traits[index]->ChildPtr(3))
  157. .Add(4, Traits[index]->ChildPtr(4))
  158. .Add(5, Traits[index]->ChildPtr(5))
  159. .Add(6, Traits[index]->ChildPtr(6))
  160. .Add(7, Traits[index]->ChildPtr(7))
  161. .Seal()
  162. .Build();
  163. newAggregatedColumnsItems[index] = Ctx.ChangeChild(*(newAggregatedColumnsItems[index]), 1, std::move(newTrait));
  164. }
  165. }
  166. return Ctx.ChangeChild(*Node, 2, Ctx.NewList(Node->Pos(), std::move(newAggregatedColumnsItems)));
  167. }
  168. TExprNode::TPtr TAggregateExpander::GetContextLambda()
  169. {
  170. return HasContextFuncs(*AggregatedColumns) ?
  171. Ctx.Builder(Node->Pos())
  172. .Lambda()
  173. .Param("stream")
  174. .Callable("WithContext")
  175. .Arg(0, "stream")
  176. .Atom(1, "Agg")
  177. .Seal()
  178. .Seal()
  179. .Build() :
  180. Ctx.Builder(Node->Pos())
  181. .Lambda()
  182. .Param("stream")
  183. .Arg("stream")
  184. .Seal()
  185. .Build();
  186. }
  187. void TAggregateExpander::ProcessSessionSetting(TExprNode::TPtr sessionSetting)
  188. {
  189. if (!sessionSetting) {
  190. return;
  191. }
  192. HaveSessionSetting = true;
  193. YQL_ENSURE(sessionSetting->Child(1)->Child(0)->IsAtom());
  194. SessionOutputColumn = sessionSetting->Child(1)->Child(0)->Content();
  195. // remove session column from other keys
  196. TExprNodeList keyColumnsList = KeyColumns->ChildrenList();
  197. EraseIf(keyColumnsList, [&](const auto& key) { return SessionOutputColumn == key->Content(); });
  198. KeyColumns = Ctx.NewList(KeyColumns->Pos(), std::move(keyColumnsList));
  199. SessionWindowParams.Traits = sessionSetting->Child(1)->ChildPtr(1);
  200. ExtractSessionWindowParams(Node->Pos(), SessionWindowParams, Ctx);
  201. ExtractSortKeyAndOrder(Node->Pos(), SessionWindowParams.SortTraits, SortParams, Ctx);
  202. if (HaveDistinct) {
  203. auto keySelector = BuildKeySelector(Node->Pos(), *OriginalRowType, KeyColumns, Ctx);
  204. const auto sessionStartMemberLambda = AddSessionParamsMemberLambda(Node->Pos(), SessionStartMemberName, keySelector,
  205. SessionWindowParams, Ctx);
  206. AggList = Ctx.Builder(Node->Pos())
  207. .Callable("PartitionsByKeys")
  208. .Add(0, AggList)
  209. .Add(1, keySelector)
  210. .Add(2, SortParams.Order)
  211. .Add(3, SortParams.Key)
  212. .Lambda(4)
  213. .Param("partitionedStream")
  214. .Apply(sessionStartMemberLambda)
  215. .With(0, "partitionedStream")
  216. .Seal()
  217. .Seal()
  218. .Seal()
  219. .Build();
  220. auto keyColumnsList = KeyColumns->ChildrenList();
  221. keyColumnsList.push_back(Ctx.NewAtom(Node->Pos(), SessionStartMemberName));
  222. KeyColumns = Ctx.NewList(Node->Pos(), std::move(keyColumnsList));
  223. RowItems.push_back(Ctx.MakeType<TItemExprType>(SessionStartMemberName, SessionWindowParams.KeyType));
  224. SessionWindowParams.Reset();
  225. SortParams.Key = SortParams.Order = VoidNode;
  226. } else {
  227. EffectiveCompact = true;
  228. }
  229. }
  230. TVector<const TTypeAnnotationNode*> TAggregateExpander::GetKeyItemTypes()
  231. {
  232. TVector<const TTypeAnnotationNode*> keyItemTypes;
  233. for (auto keyColumn : KeyColumns->Children()) {
  234. auto index = RowType->FindItem(keyColumn->Content());
  235. YQL_ENSURE(index, "Unknown column: " << keyColumn->Content());
  236. auto type = RowType->GetItems()[*index]->GetItemType();
  237. keyItemTypes.push_back(type);
  238. }
  239. return keyItemTypes;
  240. }
  241. bool TAggregateExpander::IsNeedPickle(const TVector<const TTypeAnnotationNode*>& keyItemTypes)
  242. {
  243. bool needPickle = false;
  244. for (auto type : keyItemTypes) {
  245. needPickle |= !IsDataOrOptionalOfData(type);
  246. }
  247. return needPickle;
  248. }
  249. TExprNode::TPtr TAggregateExpander::GetKeyExtractor(bool needPickle)
  250. {
  251. TExprNode::TPtr keyExtractor = Ctx.Builder(Node->Pos())
  252. .Lambda()
  253. .Param("item")
  254. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  255. if (KeyColumns->ChildrenSize() == 0) {
  256. return parent.Callable("Uint32").Atom(0, "0", TNodeFlags::Default).Seal();
  257. }
  258. else if (KeyColumns->ChildrenSize() == 1) {
  259. return parent.Callable("Member").Arg(0, "item").Add(1, KeyColumns->HeadPtr()).Seal();
  260. }
  261. else {
  262. auto listBuilder = parent.List();
  263. ui32 pos = 0;
  264. for (ui32 i = 0; i < KeyColumns->ChildrenSize(); ++i) {
  265. listBuilder
  266. .Callable(pos++, "Member")
  267. .Arg(0, "item")
  268. .Add(1, KeyColumns->ChildPtr(i))
  269. .Seal();
  270. }
  271. return listBuilder.Seal();
  272. }
  273. })
  274. .Seal()
  275. .Build();
  276. if (needPickle) {
  277. keyExtractor = Ctx.Builder(Node->Pos())
  278. .Lambda()
  279. .Param("item")
  280. .Callable("StablePickle")
  281. .Apply(0, *keyExtractor)
  282. .With(0, "item")
  283. .Seal()
  284. .Seal()
  285. .Seal()
  286. .Build();
  287. }
  288. return keyExtractor;
  289. }
  290. void TAggregateExpander::CollectColumnsSpecs()
  291. {
  292. for (ui32 index = 0; index < AggregatedColumns->ChildrenSize(); ++index) {
  293. auto child = AggregatedColumns->Child(index);
  294. if (const auto distinctField = (child->ChildrenSize() == 3) ? child->Child(2) : nullptr) {
  295. const auto ins = Distinct2Columns.emplace(distinctField->Content(), TIdxSet());
  296. if (ins.second) {
  297. DistinctFields.push_back(distinctField);
  298. }
  299. ins.first->second.insert(InitialColumnNames.size());
  300. } else {
  301. NonDistinctColumns.insert(InitialColumnNames.size());
  302. }
  303. if (child->Head().IsAtom()) {
  304. FinalColumnNames.push_back(child->HeadPtr());
  305. } else {
  306. FinalColumnNames.push_back(child->Head().HeadPtr());
  307. }
  308. InitialColumnNames.push_back(Ctx.NewAtom(FinalColumnNames.back()->Pos(), "_yql_agg_" + ToString(InitialColumnNames.size()), TNodeFlags::Default));
  309. }
  310. }
  311. void TAggregateExpander::BuildNothingStates()
  312. {
  313. for (ui32 index = 0; index < AggregatedColumns->ChildrenSize(); ++index) {
  314. auto trait = Traits[index];
  315. auto saveLambda = trait->Child(3);
  316. auto saveLambdaType = saveLambda->GetTypeAnn();
  317. auto typeNode = ExpandType(Node->Pos(), *saveLambdaType, Ctx);
  318. NothingStates.push_back(Ctx.Builder(Node->Pos())
  319. .Callable("Nothing")
  320. .Callable(0, "OptionalType")
  321. .Add(0, std::move(typeNode))
  322. .Seal()
  323. .Seal()
  324. .Build()
  325. );
  326. }
  327. }
  328. TExprNode::TPtr TAggregateExpander::GeneratePartialAggregate(const TExprNode::TPtr keyExtractor,
  329. const TVector<const TTypeAnnotationNode*>& keyItemTypes, bool needPickle)
  330. {
  331. TExprNode::TPtr pickleTypeNode = nullptr;
  332. if (needPickle) {
  333. const TTypeAnnotationNode* pickleType = nullptr;
  334. pickleType = KeyColumns->ChildrenSize() > 1 ? Ctx.MakeType<TTupleExprType>(keyItemTypes) : keyItemTypes[0];
  335. pickleTypeNode = ExpandType(Node->Pos(), *pickleType, Ctx);
  336. }
  337. TExprNode::TPtr partialAgg = nullptr;
  338. if (!NonDistinctColumns.empty()) {
  339. partialAgg = GeneratePartialAggregateForNonDistinct(keyExtractor, pickleTypeNode);
  340. }
  341. for (ui32 index = 0; index < DistinctFields.size(); ++index) {
  342. auto distinctField = DistinctFields[index];
  343. bool needDistinctPickle = EffectiveCompact ? false : needPickle;
  344. auto distinctGrouper = GenerateDistinctGrouper(distinctField, keyItemTypes, needDistinctPickle);
  345. if (!partialAgg) {
  346. partialAgg = std::move(distinctGrouper);
  347. } else {
  348. partialAgg = Ctx.Builder(Node->Pos())
  349. .Callable("Extend")
  350. .Add(0, std::move(partialAgg))
  351. .Add(1, std::move(distinctGrouper))
  352. .Seal()
  353. .Build();
  354. }
  355. }
  356. // If no aggregation functions then add additional combiner
  357. if (AggregatedColumns->ChildrenSize() == 0 && KeyColumns->ChildrenSize() > 0 && !SessionWindowParams.Update) {
  358. if (!partialAgg) {
  359. partialAgg = AggList;
  360. }
  361. auto uniqCombineInit = ReturnKeyAsIsForCombineInit(pickleTypeNode);
  362. auto uniqCombineUpdate = Ctx.Builder(Node->Pos())
  363. .Lambda()
  364. .Param("key")
  365. .Param("item")
  366. .Param("state")
  367. .Arg("state")
  368. .Seal()
  369. .Build();
  370. // Return state as-is
  371. auto uniqCombineSave = Ctx.Builder(Node->Pos())
  372. .Lambda()
  373. .Param("key")
  374. .Param("state")
  375. .Callable("Just")
  376. .Arg(0, "state")
  377. .Seal()
  378. .Seal()
  379. .Build();
  380. partialAgg = Ctx.Builder(Node->Pos())
  381. .Callable("CombineByKey")
  382. .Add(0, std::move(partialAgg))
  383. .Add(1, PreMap)
  384. .Add(2, keyExtractor)
  385. .Add(3, std::move(uniqCombineInit))
  386. .Add(4, std::move(uniqCombineUpdate))
  387. .Add(5, std::move(uniqCombineSave))
  388. .Seal()
  389. .Build();
  390. }
  391. return partialAgg;
  392. }
  393. std::function<TExprNodeBuilder& (TExprNodeBuilder&)> TAggregateExpander::GetPartialAggArgExtractor(ui32 i, bool deserialize) {
  394. return [&, i, deserialize](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  395. auto trait = Traits[i];
  396. auto extractorLambda = trait->Child(1);
  397. auto loadLambda = trait->Child(4);
  398. if (Suffix == "CombineState") {
  399. if (deserialize) {
  400. parent.Apply(*loadLambda)
  401. .With(0)
  402. .Apply(*extractorLambda)
  403. .With(0)
  404. .Callable("CastStruct")
  405. .Arg(0, "item")
  406. .Add(1, ExpandType(Node->Pos(), *extractorLambda->Head().Head().GetTypeAnn(), Ctx))
  407. .Seal()
  408. .Done()
  409. .Seal()
  410. .Done()
  411. .Seal();
  412. } else {
  413. parent.Apply(*extractorLambda)
  414. .With(0)
  415. .Callable("CastStruct")
  416. .Arg(0, "item")
  417. .Add(1, ExpandType(Node->Pos(), *extractorLambda->Head().Head().GetTypeAnn(), Ctx))
  418. .Seal()
  419. .Done()
  420. .Seal();
  421. }
  422. } else {
  423. parent.Callable("CastStruct")
  424. .Arg(0, "item")
  425. .Add(1, ExpandType(Node->Pos(), *extractorLambda->Head().Head().GetTypeAnn(), Ctx))
  426. .Seal();
  427. }
  428. return parent;
  429. };
  430. }
  431. TExprNode::TPtr TAggregateExpander::GetFinalAggStateExtractor(ui32 i) {
  432. auto trait = Traits[i];
  433. if (Suffix.StartsWith("Merge")) {
  434. auto lambda = trait->ChildPtr(1);
  435. if (!Suffix.StartsWith("MergeMany")) {
  436. return lambda;
  437. }
  438. if (lambda->Tail().IsCallable("Unwrap")) {
  439. return Ctx.Builder(Node->Pos())
  440. .Lambda()
  441. .Param("item")
  442. .ApplyPartial(lambda->HeadPtr(), lambda->Tail().HeadPtr())
  443. .With(0, "item")
  444. .Seal()
  445. .Seal()
  446. .Build();
  447. } else {
  448. return Ctx.Builder(Node->Pos())
  449. .Lambda()
  450. .Param("item")
  451. .Callable("Just")
  452. .Apply(0, *lambda)
  453. .With(0, "item")
  454. .Seal()
  455. .Seal()
  456. .Seal()
  457. .Build();
  458. }
  459. }
  460. bool aggregateOnly = (Suffix != "");
  461. const auto& columnNames = aggregateOnly ? FinalColumnNames : InitialColumnNames;
  462. return Ctx.Builder(Node->Pos())
  463. .Lambda()
  464. .Param("item")
  465. .Callable("Member")
  466. .Arg(0, "item")
  467. .Add(1, columnNames[i])
  468. .Seal()
  469. .Seal()
  470. .Build();
  471. }
  472. TExprNode::TPtr TAggregateExpander::MakeInputBlocks(const TExprNode::TPtr& stream, TExprNode::TListType& keyIdxs,
  473. TVector<TString>& outputColumns, TExprNode::TListType& aggs, bool overState, bool many, ui32* streamIdxColumn) {
  474. TVector<TString> inputColumns;
  475. auto flow = Ctx.NewCallable(Node->Pos(), "ToFlow", { stream });
  476. for (ui32 i = 0; i < RowType->GetSize(); ++i) {
  477. inputColumns.push_back(TString(RowType->GetItems()[i]->GetName()));
  478. }
  479. auto wideFlow = MakeExpandMap(Node->Pos(), inputColumns, flow, Ctx);
  480. TExprNode::TListType extractorArgs;
  481. TExprNode::TListType newRowItems;
  482. for (ui32 i = 0; i < RowType->GetSize(); ++i) {
  483. extractorArgs.push_back(Ctx.NewArgument(Node->Pos(), "field" + ToString(i)));
  484. newRowItems.push_back(Ctx.NewList(Node->Pos(), { Ctx.NewAtom(Node->Pos(), RowType->GetItems()[i]->GetName()), extractorArgs.back() }));
  485. }
  486. const TExprNode::TPtr newRow = Ctx.NewCallable(Node->Pos(), "AsStruct", std::move(newRowItems));
  487. TExprNode::TListType extractorRoots;
  488. TVector<const TTypeAnnotationNode*> allKeyTypes;
  489. for (ui32 index = 0; index < KeyColumns->ChildrenSize(); ++index) {
  490. auto keyName = KeyColumns->Child(index)->Content();
  491. auto rowIndex = RowType->FindItem(keyName);
  492. YQL_ENSURE(rowIndex, "Unknown column: " << keyName);
  493. auto type = RowType->GetItems()[*rowIndex]->GetItemType();
  494. extractorRoots.push_back(extractorArgs[*rowIndex]);
  495. allKeyTypes.push_back(type);
  496. keyIdxs.push_back(Ctx.NewAtom(Node->Pos(), ToString(index)));
  497. outputColumns.push_back(TString(keyName));
  498. }
  499. if (many) {
  500. auto rowIndex = RowType->FindItem("_yql_group_stream_index");
  501. if (!rowIndex) {
  502. return nullptr;
  503. }
  504. if (streamIdxColumn) {
  505. *streamIdxColumn = extractorRoots.size();
  506. }
  507. extractorRoots.push_back(extractorArgs[*rowIndex]);
  508. }
  509. auto outputStructType = GetSeqItemType(*Node->GetTypeAnn()).Cast<TStructExprType>();
  510. auto resolveStatus = TypesCtx.ArrowResolver->AreTypesSupported(Ctx.GetPosition(Node->Pos()), allKeyTypes, Ctx);
  511. YQL_ENSURE(resolveStatus != IArrowResolver::ERROR);
  512. if (resolveStatus != IArrowResolver::OK) {
  513. return nullptr;
  514. }
  515. for (ui32 index = 0; index < AggregatedColumns->ChildrenSize(); ++index) {
  516. auto trait = AggregatedColumns->Child(index)->ChildPtr(1);
  517. TVector<const TTypeAnnotationNode*> allTypes;
  518. const TTypeAnnotationNode* originalType = nullptr;
  519. if (overState && !trait->Child(3)->IsCallable("Void")) {
  520. auto originalExtractorType = trait->Child(3)->GetTypeAnn()->Cast<TTypeExprType>()->GetType();
  521. originalType = GetOriginalResultType(trait->Pos(), many, originalExtractorType, Ctx);
  522. YQL_ENSURE(originalType);
  523. }
  524. ui32 argsCount = trait->Child(2)->ChildrenSize() - 1;
  525. if (!overState && trait->Child(0)->Content() == "count_all") {
  526. argsCount = 0;
  527. }
  528. auto rowArg = &trait->Child(2)->Head().Head();
  529. const TNodeOnNodeOwnedMap remaps{ { rowArg, newRow } };
  530. TVector<TExprNode::TPtr> roots;
  531. for (ui32 i = 1; i < argsCount + 1; ++i) {
  532. auto root = trait->Child(2)->ChildPtr(i);
  533. allTypes.push_back(root->GetTypeAnn());
  534. auto status = RemapExpr(root, root, remaps, Ctx, TOptimizeExprSettings(&TypesCtx));
  535. YQL_ENSURE(status.Level != IGraphTransformer::TStatus::Error);
  536. roots.push_back(root);
  537. }
  538. aggs.push_back(Ctx.Builder(Node->Pos())
  539. .List()
  540. .Callable(0, TString("AggBlockApply") + (overState ? "State" : ""))
  541. .Atom(0, trait->Child(0)->Content())
  542. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  543. if (overState) {
  544. if (originalType) {
  545. parent.Add(1, ExpandType(Node->Pos(), *originalType, Ctx));
  546. } else {
  547. parent
  548. .Callable(1, "NullType")
  549. .Seal();
  550. }
  551. }
  552. return parent;
  553. })
  554. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  555. for (ui32 i = 1; i < argsCount + 1; ++i) {
  556. parent.Add(i + (overState ? 1 : 0), ExpandType(Node->Pos(), *trait->Child(2)->Child(i)->GetTypeAnn(), Ctx));
  557. }
  558. return parent;
  559. })
  560. .Seal()
  561. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  562. for (ui32 i = 1; i < argsCount + 1; ++i) {
  563. parent.Atom(i, ToString(extractorRoots.size() + i - 1));
  564. }
  565. return parent;
  566. })
  567. .Seal()
  568. .Build());
  569. for (auto root : roots) {
  570. if (many) {
  571. if (root->IsCallable("Unwrap")) {
  572. root = root->HeadPtr();
  573. } else {
  574. root = Ctx.Builder(Node->Pos())
  575. .Callable("Just")
  576. .Add(0, root)
  577. .Seal()
  578. .Build();
  579. }
  580. }
  581. extractorRoots.push_back(root);
  582. }
  583. auto outPos = outputStructType->FindItem(FinalColumnNames[index]->Content());
  584. YQL_ENSURE(outPos);
  585. allTypes.push_back(outputStructType->GetItems()[*outPos]->GetItemType());
  586. auto resolveStatus = TypesCtx.ArrowResolver->AreTypesSupported(Ctx.GetPosition(Node->Pos()), allTypes, Ctx);
  587. YQL_ENSURE(resolveStatus != IArrowResolver::ERROR);
  588. if (resolveStatus != IArrowResolver::OK) {
  589. return nullptr;
  590. }
  591. outputColumns.push_back(TString(FinalColumnNames[index]->Content()));
  592. }
  593. auto extractorLambda = Ctx.NewLambda(Node->Pos(), Ctx.NewArguments(Node->Pos(), std::move(extractorArgs)), std::move(extractorRoots));
  594. auto mappedWideFlow = Ctx.NewCallable(Node->Pos(), "WideMap", { wideFlow, extractorLambda });
  595. auto blocks = Ctx.NewCallable(Node->Pos(), "WideToBlocks", { mappedWideFlow });
  596. return blocks;
  597. }
  598. TExprNode::TPtr TAggregateExpander::TryGenerateBlockCombineAllOrHashed() {
  599. if (!TypesCtx.ArrowResolver) {
  600. return nullptr;
  601. }
  602. const bool hashed = (KeyColumns->ChildrenSize() > 0);
  603. const bool isInputList = (AggList->GetTypeAnn()->GetKind() == ETypeAnnotationKind::List);
  604. TExprNode::TListType keyIdxs;
  605. TVector<TString> outputColumns;
  606. TExprNode::TListType aggs;
  607. TExprNode::TPtr stream = nullptr;
  608. if (isInputList) {
  609. stream = Ctx.NewArgument(Node->Pos(), "stream");
  610. } else {
  611. stream = AggList;
  612. }
  613. TExprNode::TPtr blocks = MakeInputBlocks(stream, keyIdxs, outputColumns, aggs, false, false);
  614. if (!blocks) {
  615. return nullptr;
  616. }
  617. TExprNode::TPtr aggWideFlow;
  618. if (hashed) {
  619. aggWideFlow = Ctx.Builder(Node->Pos())
  620. .Callable("ToFlow")
  621. .Callable(0, "WideFromBlocks")
  622. .Callable(0, "BlockCombineHashed")
  623. .Callable(0, "FromFlow")
  624. .Add(0, blocks)
  625. .Seal()
  626. .Callable(1, "Void")
  627. .Seal()
  628. .Add(2, Ctx.NewList(Node->Pos(), std::move(keyIdxs)))
  629. .Add(3, Ctx.NewList(Node->Pos(), std::move(aggs)))
  630. .Seal()
  631. .Seal()
  632. .Seal()
  633. .Build();
  634. } else {
  635. aggWideFlow = Ctx.Builder(Node->Pos())
  636. .Callable("ToFlow")
  637. .Callable(0, "BlockCombineAll")
  638. .Callable(0, "FromFlow")
  639. .Add(0, blocks)
  640. .Seal()
  641. .Callable(1, "Void")
  642. .Seal()
  643. .Add(2, Ctx.NewList(Node->Pos(), std::move(aggs)))
  644. .Seal()
  645. .Seal()
  646. .Build();
  647. }
  648. auto finalFlow = MakeNarrowMap(Node->Pos(), outputColumns, aggWideFlow, Ctx);
  649. if (isInputList) {
  650. auto root = Ctx.NewCallable(Node->Pos(), "FromFlow", { finalFlow });
  651. auto lambdaStream = Ctx.NewLambda(Node->Pos(), Ctx.NewArguments(Node->Pos(), { stream }), std::move(root));
  652. return Ctx.Builder(Node->Pos())
  653. .Callable("LMap")
  654. .Add(0, AggList)
  655. .Lambda(1)
  656. .Param("stream")
  657. .Apply(GetContextLambda())
  658. .With(0)
  659. .Apply(lambdaStream)
  660. .With(0, "stream")
  661. .Seal()
  662. .Done()
  663. .Seal()
  664. .Seal()
  665. .Seal()
  666. .Build();
  667. } else {
  668. return finalFlow;
  669. }
  670. }
  671. TExprNode::TPtr TAggregateExpander::GeneratePartialAggregateForNonDistinct(const TExprNode::TPtr& keyExtractor, const TExprNode::TPtr& pickleTypeNode)
  672. {
  673. bool combineOnly = Suffix == "Combine" || Suffix == "CombineState";
  674. const auto& columnNames = combineOnly ? FinalColumnNames : InitialColumnNames;
  675. auto initLambdaIndex = (Suffix == "CombineState") ? 4 : 1;
  676. auto updateLambdaIndex = (Suffix == "CombineState") ? 5 : 2;
  677. auto combineInit = Ctx.Builder(Node->Pos())
  678. .Lambda()
  679. .Param("key")
  680. .Param("item")
  681. .Callable("AsStruct")
  682. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  683. ui32 ndx = 0;
  684. for (ui32 i: NonDistinctColumns) {
  685. auto trait = Traits[i];
  686. auto initLambda = trait->Child(initLambdaIndex);
  687. if (initLambda->Head().ChildrenSize() == 1) {
  688. parent.List(ndx++)
  689. .Add(0, columnNames[i])
  690. .Apply(1, *initLambda)
  691. .With(0)
  692. .Do(GetPartialAggArgExtractor(i, false))
  693. .Done()
  694. .Seal()
  695. .Seal();
  696. } else {
  697. parent.List(ndx++)
  698. .Add(0, columnNames[i])
  699. .Apply(1, *initLambda)
  700. .With(0)
  701. .Do(GetPartialAggArgExtractor(i, false))
  702. .Done()
  703. .With(1)
  704. .Callable("Uint32")
  705. .Atom(0, ToString(i), TNodeFlags::Default)
  706. .Seal()
  707. .Done()
  708. .Seal()
  709. .Seal();
  710. }
  711. }
  712. return parent;
  713. })
  714. .Seal()
  715. .Seal()
  716. .Build();
  717. auto combineUpdate = Ctx.Builder(Node->Pos())
  718. .Lambda()
  719. .Param("key")
  720. .Param("item")
  721. .Param("state")
  722. .Callable("AsStruct")
  723. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  724. ui32 ndx = 0;
  725. for (ui32 i: NonDistinctColumns) {
  726. auto trait = Traits[i];
  727. auto updateLambda = trait->Child(updateLambdaIndex);
  728. if (updateLambda->Head().ChildrenSize() == 2) {
  729. parent.List(ndx++)
  730. .Add(0, columnNames[i])
  731. .Apply(1, *updateLambda)
  732. .With(0)
  733. .Do(GetPartialAggArgExtractor(i, true))
  734. .Done()
  735. .With(1)
  736. .Callable("Member")
  737. .Arg(0, "state")
  738. .Add(1, columnNames[i])
  739. .Seal()
  740. .Done()
  741. .Seal()
  742. .Seal();
  743. } else {
  744. parent.List(ndx++)
  745. .Add(0, columnNames[i])
  746. .Apply(1, *updateLambda)
  747. .With(0)
  748. .Do(GetPartialAggArgExtractor(i, true))
  749. .Done()
  750. .With(1)
  751. .Callable("Member")
  752. .Arg(0, "state")
  753. .Add(1, columnNames[i])
  754. .Seal()
  755. .Done()
  756. .With(2)
  757. .Callable("Uint32")
  758. .Atom(0, ToString(i), TNodeFlags::Default)
  759. .Seal()
  760. .Done()
  761. .Seal()
  762. .Seal();
  763. }
  764. }
  765. return parent;
  766. })
  767. .Seal()
  768. .Seal()
  769. .Build();
  770. auto combineSave = Ctx.Builder(Node->Pos())
  771. .Lambda()
  772. .Param("key")
  773. .Param("state")
  774. .Callable("Just")
  775. .Callable(0, "AsStruct")
  776. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  777. for (ui32 i = 0; i < columnNames.size(); ++i) {
  778. if (NonDistinctColumns.find(i) == NonDistinctColumns.end()) {
  779. parent.List(i)
  780. .Add(0, columnNames[i])
  781. .Add(1, NothingStates[i])
  782. .Seal();
  783. } else {
  784. auto trait = Traits[i];
  785. auto saveLambda = trait->Child(3);
  786. if (!DistinctFields.empty()) {
  787. parent.List(i)
  788. .Add(0, columnNames[i])
  789. .Callable(1, "Just")
  790. .Apply(0, *saveLambda)
  791. .With(0)
  792. .Callable("Member")
  793. .Arg(0, "state")
  794. .Add(1, columnNames[i])
  795. .Seal()
  796. .Done()
  797. .Seal()
  798. .Seal()
  799. .Seal();
  800. } else {
  801. parent.List(i)
  802. .Add(0, columnNames[i])
  803. .Apply(1, *saveLambda)
  804. .With(0)
  805. .Callable("Member")
  806. .Arg(0, "state")
  807. .Add(1, columnNames[i])
  808. .Seal()
  809. .Done()
  810. .Seal()
  811. .Seal();
  812. }
  813. }
  814. }
  815. return parent;
  816. })
  817. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  818. ui32 pos = 0;
  819. for (ui32 i = 0; i < KeyColumns->ChildrenSize(); ++i) {
  820. auto listBuilder = parent.List(columnNames.size() + i);
  821. listBuilder.Add(0, KeyColumns->ChildPtr(i));
  822. if (KeyColumns->ChildrenSize() > 1) {
  823. if (pickleTypeNode) {
  824. listBuilder
  825. .Callable(1, "Nth")
  826. .Callable(0, "Unpickle")
  827. .Add(0, pickleTypeNode)
  828. .Arg(1, "key")
  829. .Seal()
  830. .Atom(1, ToString(pos), TNodeFlags::Default)
  831. .Seal();
  832. } else {
  833. listBuilder
  834. .Callable(1, "Nth")
  835. .Arg(0, "key")
  836. .Atom(1, ToString(pos), TNodeFlags::Default)
  837. .Seal();
  838. }
  839. ++pos;
  840. } else {
  841. if (pickleTypeNode) {
  842. listBuilder.Callable(1, "Unpickle")
  843. .Add(0, pickleTypeNode)
  844. .Arg(1, "key")
  845. .Seal();
  846. } else {
  847. listBuilder.Arg(1, "key");
  848. }
  849. }
  850. listBuilder.Seal();
  851. }
  852. return parent;
  853. })
  854. .Seal()
  855. .Seal()
  856. .Seal()
  857. .Build();
  858. return Ctx.Builder(Node->Pos())
  859. .Callable("CombineByKey")
  860. .Add(0, AggList)
  861. .Add(1, PreMap)
  862. .Add(2, keyExtractor)
  863. .Add(3, std::move(combineInit))
  864. .Add(4, std::move(combineUpdate))
  865. .Add(5, std::move(combineSave))
  866. .Seal()
  867. .Build();
  868. }
  869. void TAggregateExpander::GenerateInitForDistinct(TExprNodeBuilder& parent, ui32& ndx, const TIdxSet& indicies, const TExprNode::TPtr& distinctField) {
  870. for (ui32 i: indicies) {
  871. auto trait = Traits[i];
  872. auto initLambda = trait->Child(1);
  873. if (initLambda->Head().ChildrenSize() == 1) {
  874. parent.List(ndx++)
  875. .Add(0, InitialColumnNames[i])
  876. .Apply(1, *initLambda)
  877. .With(0)
  878. .Callable("Member")
  879. .Arg(0, "item")
  880. .Add(1, distinctField)
  881. .Seal()
  882. .Done()
  883. .Seal()
  884. .Seal();
  885. } else {
  886. parent.List(ndx++)
  887. .Add(0, InitialColumnNames[i])
  888. .Apply(1, *initLambda)
  889. .With(0)
  890. .Callable("Member")
  891. .Arg(0, "item")
  892. .Add(1, distinctField)
  893. .Seal()
  894. .Done()
  895. .With(1)
  896. .Callable("Uint32")
  897. .Atom(0, ToString(i), TNodeFlags::Default)
  898. .Seal()
  899. .Done()
  900. .Seal()
  901. .Seal();
  902. }
  903. }
  904. }
  905. TExprNode::TPtr TAggregateExpander::GenerateDistinctGrouper(const TExprNode::TPtr distinctField,
  906. const TVector<const TTypeAnnotationNode*>& keyItemTypes, bool needDistinctPickle)
  907. {
  908. auto& indicies = Distinct2Columns[distinctField->Content()];
  909. auto distinctIndex = RowType->FindItem(distinctField->Content());
  910. YQL_ENSURE(distinctIndex, "Unknown field: " << distinctField->Content());
  911. auto distinctType = RowType->GetItems()[*distinctIndex]->GetItemType();
  912. TVector<const TTypeAnnotationNode*> distinctKeyItemTypes = keyItemTypes;
  913. distinctKeyItemTypes.push_back(distinctType);
  914. auto valueType = distinctType;
  915. if (distinctType->GetKind() == ETypeAnnotationKind::Optional) {
  916. distinctType = distinctType->Cast<TOptionalExprType>()->GetItemType();
  917. }
  918. if (distinctType->GetKind() != ETypeAnnotationKind::Data) {
  919. needDistinctPickle = true;
  920. valueType = Ctx.MakeType<TDataExprType>(EDataSlot::String);
  921. }
  922. const auto expandedValueType = needDistinctPickle ?
  923. Ctx.Builder(Node->Pos())
  924. .Callable("DataType")
  925. .Atom(0, "String", TNodeFlags::Default)
  926. .Seal()
  927. .Build()
  928. : ExpandType(Node->Pos(), *valueType, Ctx);
  929. DistinctFieldNeedsPickle[distinctField->Content()] = needDistinctPickle;
  930. auto udfSetCreateValue = Ctx.Builder(Node->Pos())
  931. .Callable("Udf")
  932. .Atom(0, "Set.Create")
  933. .Callable(1, "Void").Seal()
  934. .Callable(2, "TupleType")
  935. .Callable(0, "TupleType")
  936. .Add(0, expandedValueType)
  937. .Callable(1, "DataType")
  938. .Atom(0, "Uint32", TNodeFlags::Default)
  939. .Seal()
  940. .Seal()
  941. .Callable(1, "StructType").Seal()
  942. .Add(2, expandedValueType)
  943. .Seal()
  944. .Seal()
  945. .Build();
  946. UdfSetCreate[distinctField->Content()] = udfSetCreateValue;
  947. auto resourceType = Ctx.Builder(Node->Pos())
  948. .Callable("TypeOf")
  949. .Callable(0, "Apply")
  950. .Add(0, udfSetCreateValue)
  951. .Callable(1, "InstanceOf")
  952. .Add(0, expandedValueType)
  953. .Seal()
  954. .Callable(2, "Uint32")
  955. .Atom(0, "0", TNodeFlags::Default)
  956. .Seal()
  957. .Seal()
  958. .Seal()
  959. .Build();
  960. UdfAddValue[distinctField->Content()] = Ctx.Builder(Node->Pos())
  961. .Callable("Udf")
  962. .Atom(0, "Set.AddValue")
  963. .Callable(1, "Void").Seal()
  964. .Callable(2, "TupleType")
  965. .Callable(0, "TupleType")
  966. .Add(0, resourceType)
  967. .Add(1, expandedValueType)
  968. .Seal()
  969. .Callable(1, "StructType").Seal()
  970. .Add(2, expandedValueType)
  971. .Seal()
  972. .Seal()
  973. .Build();
  974. UdfWasChanged[distinctField->Content()] = Ctx.Builder(Node->Pos())
  975. .Callable("Udf")
  976. .Atom(0, "Set.WasChanged")
  977. .Callable(1, "Void").Seal()
  978. .Callable(2, "TupleType")
  979. .Callable(0, "TupleType")
  980. .Add(0, resourceType)
  981. .Seal()
  982. .Callable(1, "StructType").Seal()
  983. .Add(2, expandedValueType)
  984. .Seal()
  985. .Seal()
  986. .Build();
  987. auto distinctKeyExtractor = Ctx.Builder(Node->Pos())
  988. .Lambda()
  989. .Param("item")
  990. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  991. if (KeyColumns->ChildrenSize() != 0) {
  992. auto listBuilder = parent.List();
  993. ui32 pos = 0;
  994. for (ui32 i = 0; i < KeyColumns->ChildrenSize(); ++i) {
  995. listBuilder
  996. .Callable(pos++, "Member")
  997. .Arg(0, "item")
  998. .Add(1, KeyColumns->ChildPtr(i))
  999. .Seal();
  1000. }
  1001. listBuilder
  1002. .Callable(pos, "Member")
  1003. .Arg(0, "item")
  1004. .Add(1, distinctField)
  1005. .Seal();
  1006. return listBuilder.Seal();
  1007. } else {
  1008. return parent
  1009. .Callable("Member")
  1010. .Arg(0, "item")
  1011. .Add(1, distinctField)
  1012. .Seal();
  1013. }
  1014. })
  1015. .Seal()
  1016. .Build();
  1017. const TTypeAnnotationNode* distinctPickleType = nullptr;
  1018. TExprNode::TPtr distinctPickleTypeNode;
  1019. if (needDistinctPickle) {
  1020. distinctPickleType = KeyColumns->ChildrenSize() > 0 ? Ctx.MakeType<TTupleExprType>(distinctKeyItemTypes) : distinctKeyItemTypes.front();
  1021. distinctPickleTypeNode = ExpandType(Node->Pos(), *distinctPickleType, Ctx);
  1022. }
  1023. if (needDistinctPickle) {
  1024. distinctKeyExtractor = Ctx.Builder(Node->Pos())
  1025. .Lambda()
  1026. .Param("item")
  1027. .Callable("StablePickle")
  1028. .Apply(0, *distinctKeyExtractor).With(0, "item").Seal()
  1029. .Seal()
  1030. .Seal()
  1031. .Build();
  1032. }
  1033. auto distinctCombineInit = Ctx.Builder(Node->Pos())
  1034. .Lambda()
  1035. .Param("key")
  1036. .Param("item")
  1037. .Callable("AsStruct")
  1038. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1039. ui32 ndx = 0;
  1040. GenerateInitForDistinct(parent, ndx, indicies, distinctField);
  1041. return parent;
  1042. })
  1043. .Seal()
  1044. .Seal()
  1045. .Build();
  1046. auto distinctCombineUpdate = Ctx.Builder(Node->Pos())
  1047. .Lambda()
  1048. .Param("key")
  1049. .Param("item")
  1050. .Param("state")
  1051. .Arg("state")
  1052. .Seal()
  1053. .Build();
  1054. ui32 ndx = 0;
  1055. auto distinctCombineSave = Ctx.Builder(Node->Pos())
  1056. .Lambda()
  1057. .Param("key")
  1058. .Param("state")
  1059. .Callable("Just")
  1060. .Callable(0, "AsStruct")
  1061. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1062. for (ui32 i: indicies) {
  1063. auto trait = Traits[i];
  1064. auto saveLambda = trait->Child(3);
  1065. parent.List(ndx++)
  1066. .Add(0, InitialColumnNames[i])
  1067. .Apply(1, *saveLambda)
  1068. .With(0)
  1069. .Callable("Member")
  1070. .Arg(0, "state")
  1071. .Add(1, InitialColumnNames[i])
  1072. .Seal()
  1073. .Done()
  1074. .Seal()
  1075. .Seal();
  1076. }
  1077. return parent;
  1078. })
  1079. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1080. if (KeyColumns->ChildrenSize() > 0) {
  1081. if (needDistinctPickle) {
  1082. ui32 pos = 0;
  1083. for (ui32 i = 0; i < KeyColumns->ChildrenSize(); ++i) {
  1084. parent.List(ndx++)
  1085. .Add(0, KeyColumns->ChildPtr(i))
  1086. .Callable(1, "Nth")
  1087. .Callable(0, "Unpickle")
  1088. .Add(0, distinctPickleTypeNode)
  1089. .Arg(1, "key")
  1090. .Seal()
  1091. .Atom(1, ToString(pos++), TNodeFlags::Default)
  1092. .Seal()
  1093. .Seal();
  1094. }
  1095. parent.List(ndx++)
  1096. .Add(0, distinctField)
  1097. .Callable(1, "Nth")
  1098. .Callable(0, "Unpickle")
  1099. .Add(0, distinctPickleTypeNode)
  1100. .Arg(1, "key")
  1101. .Seal()
  1102. .Atom(1, ToString(pos++), TNodeFlags::Default)
  1103. .Seal()
  1104. .Seal();
  1105. } else {
  1106. ui32 pos = 0;
  1107. for (ui32 i = 0; i < KeyColumns->ChildrenSize(); ++i) {
  1108. parent.List(ndx++)
  1109. .Add(0, KeyColumns->ChildPtr(i))
  1110. .Callable(1, "Nth")
  1111. .Arg(0, "key")
  1112. .Atom(1, ToString(pos++), TNodeFlags::Default)
  1113. .Seal()
  1114. .Seal();
  1115. }
  1116. parent.List(ndx++)
  1117. .Add(0, distinctField)
  1118. .Callable(1, "Nth")
  1119. .Arg(0, "key")
  1120. .Atom(1, ToString(pos++), TNodeFlags::Default)
  1121. .Seal()
  1122. .Seal();
  1123. }
  1124. } else {
  1125. if (needDistinctPickle) {
  1126. parent.List(ndx++)
  1127. .Add(0, distinctField)
  1128. .Callable(1, "Unpickle")
  1129. .Add(0, distinctPickleTypeNode)
  1130. .Arg(1, "key")
  1131. .Seal()
  1132. .Seal();
  1133. } else {
  1134. parent.List(ndx++)
  1135. .Add(0, distinctField)
  1136. .Arg(1, "key")
  1137. .Seal();
  1138. }
  1139. }
  1140. return parent;
  1141. })
  1142. .Seal()
  1143. .Seal()
  1144. .Seal()
  1145. .Build();
  1146. auto distinctCombiner = Ctx.Builder(Node->Pos())
  1147. .Callable("CombineByKey")
  1148. .Add(0, AggList)
  1149. .Add(1, PreMap)
  1150. .Add(2, distinctKeyExtractor)
  1151. .Add(3, std::move(distinctCombineInit))
  1152. .Add(4, std::move(distinctCombineUpdate))
  1153. .Add(5, std::move(distinctCombineSave))
  1154. .Seal()
  1155. .Build();
  1156. auto distinctGrouper = Ctx.Builder(Node->Pos())
  1157. .Callable("PartitionsByKeys")
  1158. .Add(0, std::move(distinctCombiner))
  1159. .Add(1, distinctKeyExtractor)
  1160. .Callable(2, "Void").Seal()
  1161. .Callable(3, "Void").Seal()
  1162. .Lambda(4)
  1163. .Param("groups")
  1164. .Callable("Map")
  1165. .Callable(0, "Condense1")
  1166. .Arg(0, "groups")
  1167. .Lambda(1)
  1168. .Param("item")
  1169. .Arg("item")
  1170. .Seal()
  1171. .Lambda(2)
  1172. .Param("item")
  1173. .Param("state")
  1174. .Callable("IsKeySwitch")
  1175. .Arg(0, "item")
  1176. .Arg(1, "state")
  1177. .Add(2, distinctKeyExtractor)
  1178. .Add(3, distinctKeyExtractor)
  1179. .Seal()
  1180. .Seal()
  1181. .Lambda(3)
  1182. .Param("item")
  1183. .Param("state")
  1184. .Arg("item")
  1185. .Seal()
  1186. .Seal()
  1187. .Lambda(1)
  1188. .Param("state")
  1189. .Callable("AsStruct")
  1190. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1191. for (ui32 i = 0; i < InitialColumnNames.size(); ++i) {
  1192. if (indicies.find(i) != indicies.end()) {
  1193. parent.List(i)
  1194. .Add(0, InitialColumnNames[i])
  1195. .Callable(1, "Just")
  1196. .Callable(0, "Member")
  1197. .Arg(0, "state")
  1198. .Add(1, InitialColumnNames[i])
  1199. .Seal()
  1200. .Seal()
  1201. .Seal();
  1202. } else {
  1203. parent.List(i)
  1204. .Add(0, InitialColumnNames[i])
  1205. .Add(1, NothingStates[i])
  1206. .Seal();
  1207. }
  1208. }
  1209. return parent;
  1210. })
  1211. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1212. if (KeyColumns->ChildrenSize() > 0) {
  1213. for (ui32 i = 0; i < KeyColumns->ChildrenSize(); ++i) {
  1214. parent.List(InitialColumnNames.size() + i)
  1215. .Add(0, KeyColumns->ChildPtr(i))
  1216. .Callable(1, "Member")
  1217. .Arg(0, "state")
  1218. .Add(1, KeyColumns->ChildPtr(i))
  1219. .Seal().Seal();
  1220. }
  1221. }
  1222. return parent;
  1223. })
  1224. .Seal()
  1225. .Seal()
  1226. .Seal()
  1227. .Seal()
  1228. .Seal()
  1229. .Build();
  1230. return distinctGrouper;
  1231. }
  1232. TExprNode::TPtr TAggregateExpander::ReturnKeyAsIsForCombineInit(const TExprNode::TPtr& pickleTypeNode)
  1233. {
  1234. return Ctx.Builder(Node->Pos())
  1235. .Lambda()
  1236. .Param("key")
  1237. .Param("item")
  1238. .Callable("AsStruct")
  1239. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1240. ui32 pos = 0;
  1241. for (ui32 i = 0; i < KeyColumns->ChildrenSize(); ++i) {
  1242. auto listBuilder = parent.List(i);
  1243. listBuilder.Add(0, KeyColumns->Child(i));
  1244. if (KeyColumns->ChildrenSize() > 1) {
  1245. if (pickleTypeNode) {
  1246. listBuilder
  1247. .Callable(1, "Nth")
  1248. .Callable(0, "Unpickle")
  1249. .Add(0, pickleTypeNode)
  1250. .Arg(1, "key")
  1251. .Seal()
  1252. .Atom(1, ToString(pos++), TNodeFlags::Default)
  1253. .Seal();
  1254. } else {
  1255. listBuilder
  1256. .Callable(1, "Nth")
  1257. .Arg(0, "key")
  1258. .Atom(1, ToString(pos++), TNodeFlags::Default)
  1259. .Seal();
  1260. }
  1261. } else {
  1262. if (pickleTypeNode) {
  1263. listBuilder.Callable(1, "Unpickle")
  1264. .Add(0, pickleTypeNode)
  1265. .Arg(1, "key")
  1266. .Seal();
  1267. } else {
  1268. listBuilder.Arg(1, "key");
  1269. }
  1270. }
  1271. listBuilder.Seal();
  1272. }
  1273. return parent;
  1274. })
  1275. .Seal()
  1276. .Seal()
  1277. .Build();
  1278. }
  1279. TExprNode::TPtr TAggregateExpander::BuildFinalizeByKeyLambda(const TExprNode::TPtr& preprocessLambda, const TExprNode::TPtr& keyExtractor) {
  1280. return Ctx.Builder(Node->Pos())
  1281. .Lambda()
  1282. .Param("stream")
  1283. .Callable("FinalizeByKey")
  1284. .Arg(0, "stream")
  1285. .Lambda(1)
  1286. .Param("item")
  1287. .Callable("Just")
  1288. .Apply(0, preprocessLambda)
  1289. .With(0, "item")
  1290. .Seal()
  1291. .Seal()
  1292. .Seal()
  1293. .Add(2, keyExtractor)
  1294. .Lambda(3)
  1295. .Param("key")
  1296. .Param("item")
  1297. .Apply(GeneratePostAggregateInitPhase())
  1298. .With(0, "item")
  1299. .Seal()
  1300. .Seal()
  1301. .Lambda(4)
  1302. .Param("key")
  1303. .Param("item")
  1304. .Param("state")
  1305. .Apply(GeneratePostAggregateMergePhase())
  1306. .With(0, "item")
  1307. .With(1, "state")
  1308. .Seal()
  1309. .Seal()
  1310. .Lambda(5)
  1311. .Param("key")
  1312. .Param("state")
  1313. .Apply(GeneratePostAggregateSavePhase())
  1314. .With(0, "state")
  1315. .Seal()
  1316. .Seal()
  1317. .Seal()
  1318. .Seal().Build();
  1319. }
  1320. TExprNode::TPtr TAggregateExpander::CountAggregateRewrite(const NNodes::TCoAggregate& node, TExprContext& ctx, bool useBlocks) {
  1321. auto keyColumns = node.Keys();
  1322. auto aggregatedColumns = node.Handlers();
  1323. if (keyColumns.Size() > 0 || aggregatedColumns.Size() != 1) {
  1324. return node.Ptr();
  1325. }
  1326. auto settings = node.Settings();
  1327. auto hoppingSetting = GetSetting(settings.Ref(), "hopping");
  1328. if (hoppingSetting) {
  1329. return node.Ptr();
  1330. }
  1331. if (GetSetting(settings.Ref(), "session")) {
  1332. // TODO: support
  1333. return node.Ptr();
  1334. }
  1335. auto aggregatedColumn = aggregatedColumns.Item(0);
  1336. const bool isDistinct = (aggregatedColumn.Ref().ChildrenSize() == 3);
  1337. auto traits = aggregatedColumn.Ref().Child(1);
  1338. auto outputColumn = aggregatedColumn.Ref().HeadPtr();
  1339. // validation of traits
  1340. const TTypeAnnotationNode* inputItemType;
  1341. bool onlyColumn = true;
  1342. bool onlyZero = true;
  1343. TExprNode::TPtr initVal;
  1344. if (traits->IsCallable("AggregationTraits")) {
  1345. inputItemType = traits->Head().GetTypeAnn()->Cast<TTypeExprType>()->GetType();
  1346. auto init = NNodes::TCoLambda(traits->Child(1));
  1347. TExprNode::TPtr updateVal;
  1348. if (init.Body().Ref().IsCallable("Uint64") &&
  1349. init.Body().Ref().Head().Content() == "1") {
  1350. onlyZero = false;
  1351. } else if (init.Body().Ref().IsCallable("Uint64") &&
  1352. init.Body().Ref().Head().Content() == "0") {
  1353. onlyColumn = false;
  1354. } else if (init.Body().Ref().IsCallable("AggrCountInit")) {
  1355. initVal = init.Body().Ref().HeadPtr();
  1356. onlyColumn = onlyColumn && init.Body().Ref().Child(0) == init.Args().Arg(0).Raw();
  1357. onlyZero = false;
  1358. } else {
  1359. return node.Ptr();
  1360. }
  1361. auto update = NNodes::TCoLambda(traits->Child(2));
  1362. auto inc = update.Body().Ptr();
  1363. if (inc->IsCallable("Inc") && inc->Child(0) == update.Args().Arg(1).Raw()) {
  1364. onlyZero = false;
  1365. } else if (inc->IsCallable("AggrCountUpdate") && inc->Child(1) == update.Args().Arg(1).Raw()) {
  1366. updateVal = inc->HeadPtr();
  1367. onlyColumn = onlyColumn && inc->Child(0) == update.Args().Arg(0).Raw();
  1368. onlyZero = false;
  1369. } else if (inc == update.Args().Arg(1).Raw()) {
  1370. onlyColumn = false;
  1371. } else {
  1372. return node.Ptr();
  1373. }
  1374. auto save = NNodes::TCoLambda(traits->Child(3));
  1375. if (save.Body().Raw() != save.Args().Arg(0).Raw()) {
  1376. return node.Ptr();
  1377. }
  1378. auto load = NNodes::TCoLambda(traits->Child(4));
  1379. if (load.Body().Raw() != load.Args().Arg(0).Raw()) {
  1380. return node.Ptr();
  1381. }
  1382. auto merge = NNodes::TCoLambda(traits->Child(5));
  1383. {
  1384. auto& plus = merge.Body().Ref();
  1385. if (!plus.IsCallable({ "+", "AggrAdd" }) ) {
  1386. return node.Ptr();
  1387. }
  1388. if (!(plus.Child(0) == merge.Args().Arg(0).Raw() &&
  1389. plus.Child(1) == merge.Args().Arg(1).Raw())) {
  1390. return node.Ptr();
  1391. }
  1392. }
  1393. auto finish = NNodes::TCoLambda(traits->Child(6));
  1394. if (finish.Body().Raw() != finish.Args().Arg(0).Raw()) {
  1395. return node.Ptr();
  1396. }
  1397. auto defVal = traits->Child(7);
  1398. if (!defVal->IsCallable("Uint64") || defVal->Head().Content() != "0") {
  1399. return node.Ptr();
  1400. }
  1401. if (!isDistinct) {
  1402. if (!onlyZero && !onlyColumn) {
  1403. if (!initVal || !updateVal || initVal != updateVal) {
  1404. return node.Ptr();
  1405. }
  1406. }
  1407. }
  1408. } else if (traits->IsCallable("AggApply")) {
  1409. if (traits->Head().Content() != "count_all" && traits->Head().Content() != "count") {
  1410. return node.Ptr();
  1411. }
  1412. inputItemType = traits->Child(1)->GetTypeAnn()->Cast<TTypeExprType>()->GetType();
  1413. onlyZero = false;
  1414. onlyColumn = false;
  1415. if (&traits->Child(2)->Head().Head() == &traits->Child(2)->Tail()) {
  1416. onlyColumn = true;
  1417. }
  1418. if (!isDistinct) {
  1419. if (traits->Head().Content() == "count") {
  1420. initVal = traits->Child(2)->TailPtr();
  1421. if (initVal->GetTypeAnn()->IsOptionalOrNull()) {
  1422. if (IsDepended(traits->Child(2)->Tail(), traits->Child(2)->Head().Head())) {
  1423. return node.Ptr();
  1424. }
  1425. } else {
  1426. initVal = nullptr;
  1427. }
  1428. }
  1429. }
  1430. } else {
  1431. return node.Ptr();
  1432. }
  1433. const bool isOptionalColumn = inputItemType->GetKind() == ETypeAnnotationKind::Optional;
  1434. if (!isDistinct) {
  1435. auto length = ctx.Builder(node.Pos())
  1436. .Callable("Length")
  1437. .Add(0, node.Input().Ptr())
  1438. .Seal()
  1439. .Build();
  1440. if (onlyZero) {
  1441. length = ctx.Builder(node.Pos())
  1442. .Callable("Uint64")
  1443. .Atom(0, "0", TNodeFlags::Default)
  1444. .Seal()
  1445. .Build();
  1446. } else if (!onlyColumn && initVal) {
  1447. length = ctx.Builder(node.Pos())
  1448. .Callable("If")
  1449. .Callable(0, "Exists")
  1450. .Add(0, initVal)
  1451. .Seal()
  1452. .Add(1, std::move(length))
  1453. .Callable(2, "Uint64")
  1454. .Atom(0, "0", TNodeFlags::Default)
  1455. .Seal()
  1456. .Seal()
  1457. .Build();
  1458. }
  1459. auto ret = ctx.Builder(node.Pos())
  1460. .Callable("AsList")
  1461. .Callable(0, "AsStruct")
  1462. .List(0)
  1463. .Add(0, std::move(outputColumn))
  1464. .Add(1, std::move(length))
  1465. .Seal()
  1466. .Seal()
  1467. .Seal()
  1468. .Build();
  1469. return ret;
  1470. }
  1471. if (useBlocks || !onlyColumn) {
  1472. return node.Ptr();
  1473. }
  1474. auto removedOptionalType = inputItemType;
  1475. if (isOptionalColumn) {
  1476. removedOptionalType = removedOptionalType->Cast<TOptionalExprType>()->GetItemType();
  1477. }
  1478. const bool needPickle = removedOptionalType->GetKind() != ETypeAnnotationKind::Data;
  1479. auto pickleTypeNode = ExpandType(node.Pos(), *inputItemType, ctx);
  1480. auto distictColumn = aggregatedColumn.Ref().ChildPtr(2);
  1481. auto combine = ctx.Builder(node.Pos())
  1482. .Callable("CombineByKey")
  1483. .Callable(0, "ExtractMembers")
  1484. .Add(0, node.Input().Ptr())
  1485. .List(1)
  1486. .Add(0, distictColumn)
  1487. .Seal()
  1488. .Seal()
  1489. .Lambda(1)
  1490. .Param("row")
  1491. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1492. if (isOptionalColumn) {
  1493. parent.Callable("Map")
  1494. .Callable(0, "Member")
  1495. .Arg(0, "row")
  1496. .Add(1, distictColumn)
  1497. .Seal()
  1498. .Lambda(1)
  1499. .Param("unpacked")
  1500. .Arg("unpacked")
  1501. .Seal()
  1502. .Seal();
  1503. } else {
  1504. parent.Callable("Just")
  1505. .Callable(0, "Member")
  1506. .Arg(0, "row")
  1507. .Add(1, distictColumn)
  1508. .Seal()
  1509. .Seal();
  1510. }
  1511. return parent;
  1512. })
  1513. .Seal()
  1514. .Lambda(2)
  1515. .Param("item")
  1516. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1517. if (needPickle) {
  1518. parent.Callable("StablePickle")
  1519. .Arg(0, "item")
  1520. .Seal();
  1521. } else {
  1522. parent.Arg("item");
  1523. }
  1524. return parent;
  1525. })
  1526. .Seal()
  1527. .Lambda(3)
  1528. .Param("key")
  1529. .Param("item")
  1530. .Callable("Void")
  1531. .Seal()
  1532. .Seal()
  1533. .Lambda(4)
  1534. .Param("key")
  1535. .Param("item")
  1536. .Param("state")
  1537. .Arg("state")
  1538. .Seal()
  1539. .Lambda(5)
  1540. .Param("key")
  1541. .Param("state")
  1542. .Callable("Just")
  1543. .Callable(0, "AsStruct")
  1544. .List(0)
  1545. .Atom(0, "value")
  1546. .Arg(1, "key")
  1547. .Seal()
  1548. .Seal()
  1549. .Seal()
  1550. .Seal()
  1551. .Seal()
  1552. .Build();
  1553. auto groupByKey = ctx.Builder(node.Pos())
  1554. .Callable("PartitionByKey")
  1555. .Add(0, combine)
  1556. .Lambda(1)
  1557. .Param("combineRow")
  1558. .Callable("Member")
  1559. .Arg(0, "combineRow")
  1560. .Atom(1, "value")
  1561. .Seal()
  1562. .Seal()
  1563. .Callable(2, "Void")
  1564. .Seal()
  1565. .Callable(3, "Void")
  1566. .Seal()
  1567. .Lambda(4)
  1568. .Param("groups")
  1569. .Callable("Map")
  1570. .Arg(0, "groups")
  1571. .Lambda(1)
  1572. .Param("group")
  1573. .Callable("AsStruct")
  1574. .Seal()
  1575. .Seal()
  1576. .Seal()
  1577. .Seal()
  1578. .Seal()
  1579. .Build();
  1580. auto ret = ctx.Builder(node.Pos())
  1581. .Callable("AsList")
  1582. .Callable(0, "AsStruct")
  1583. .List(0)
  1584. .Add(0, outputColumn)
  1585. .Callable(1, "Length")
  1586. .Add(0, std::move(groupByKey))
  1587. .Seal()
  1588. .Seal()
  1589. .Seal()
  1590. .Seal()
  1591. .Build();
  1592. return ret;
  1593. }
  1594. TExprNode::TPtr TAggregateExpander::GeneratePostAggregate(const TExprNode::TPtr& preAgg, const TExprNode::TPtr& keyExtractor)
  1595. {
  1596. auto preprocessLambda = GeneratePreprocessLambda(keyExtractor);
  1597. TExprNode::TPtr postAgg;
  1598. if (!UsePartitionsByKeys && UseFinalizeByKeys && !HaveSessionSetting) {
  1599. postAgg = Ctx.Builder(Node->Pos())
  1600. .Callable("ShuffleByKeys")
  1601. .Add(0, std::move(preAgg))
  1602. .Add(1, keyExtractor)
  1603. .Lambda(2)
  1604. .Param("stream")
  1605. .Apply(GetContextLambda())
  1606. .With(0)
  1607. .Apply(BuildFinalizeByKeyLambda(preprocessLambda, keyExtractor))
  1608. .With(0, "stream")
  1609. .Seal()
  1610. .Done()
  1611. .Seal()
  1612. .Seal()
  1613. .Seal().Build();
  1614. } else {
  1615. auto condenseSwitch = GenerateCondenseSwitch(keyExtractor);
  1616. postAgg = Ctx.Builder(Node->Pos())
  1617. .Callable("PartitionsByKeys")
  1618. .Add(0, std::move(preAgg))
  1619. .Add(1, keyExtractor)
  1620. .Add(2, SortParams.Order)
  1621. .Add(3, SortParams.Key)
  1622. .Lambda(4)
  1623. .Param("stream")
  1624. .Apply(GetContextLambda())
  1625. .With(0)
  1626. .Callable("Map")
  1627. .Callable(0, "Condense1")
  1628. .Apply(0, preprocessLambda)
  1629. .With(0, "stream")
  1630. .Seal()
  1631. .Add(1, GeneratePostAggregateInitPhase())
  1632. .Add(2, condenseSwitch)
  1633. .Add(3, GeneratePostAggregateMergePhase())
  1634. .Seal()
  1635. .Add(1, GeneratePostAggregateSavePhase())
  1636. .Seal()
  1637. .Done()
  1638. .Seal()
  1639. .Seal()
  1640. .Seal().Build();
  1641. }
  1642. if (KeyColumns->ChildrenSize() == 0 && !HaveSessionSetting && (Suffix == "" || Suffix.EndsWith("Finalize"))) {
  1643. return MakeSingleGroupRow(*Node, postAgg, Ctx);
  1644. }
  1645. return postAgg;
  1646. }
  1647. TExprNode::TPtr TAggregateExpander::GeneratePreprocessLambda(const TExprNode::TPtr& keyExtractor)
  1648. {
  1649. TExprNode::TPtr preprocessLambda;
  1650. if (SessionWindowParams.Update) {
  1651. YQL_ENSURE(EffectiveCompact);
  1652. YQL_ENSURE(SessionWindowParams.Key);
  1653. YQL_ENSURE(SessionWindowParams.KeyType);
  1654. YQL_ENSURE(SessionWindowParams.Init);
  1655. preprocessLambda = AddSessionParamsMemberLambda(Node->Pos(), SessionStartMemberName, "", keyExtractor,
  1656. SessionWindowParams.Key, SessionWindowParams.Init, SessionWindowParams.Update, Ctx);
  1657. } else {
  1658. YQL_ENSURE(!SessionWindowParams.Key);
  1659. preprocessLambda = MakeIdentityLambda(Node->Pos(), Ctx);
  1660. }
  1661. return preprocessLambda;
  1662. }
  1663. TExprNode::TPtr TAggregateExpander::GenerateCondenseSwitch(const TExprNode::TPtr& keyExtractor)
  1664. {
  1665. TExprNode::TPtr condenseSwitch;
  1666. if (SessionWindowParams.Update) {
  1667. YQL_ENSURE(EffectiveCompact);
  1668. YQL_ENSURE(SessionWindowParams.Key);
  1669. YQL_ENSURE(SessionWindowParams.KeyType);
  1670. YQL_ENSURE(SessionWindowParams.Init);
  1671. condenseSwitch = Ctx.Builder(Node->Pos())
  1672. .Lambda()
  1673. .Param("item")
  1674. .Param("state")
  1675. .Callable("Or")
  1676. .Callable(0, "AggrNotEquals")
  1677. .Apply(0, keyExtractor)
  1678. .With(0, "item")
  1679. .Seal()
  1680. .Apply(1, keyExtractor)
  1681. .With(0, "state")
  1682. .Seal()
  1683. .Seal()
  1684. .Callable(1, "AggrNotEquals")
  1685. .Callable(0, "Member")
  1686. .Arg(0, "item")
  1687. .Atom(1, SessionStartMemberName)
  1688. .Seal()
  1689. .Callable(1, "Member")
  1690. .Arg(0, "state")
  1691. .Atom(1, SessionStartMemberName)
  1692. .Seal()
  1693. .Seal()
  1694. .Seal()
  1695. .Seal()
  1696. .Build();
  1697. } else {
  1698. YQL_ENSURE(!SessionWindowParams.Key);
  1699. condenseSwitch = Ctx.Builder(Node->Pos())
  1700. .Lambda()
  1701. .Param("item")
  1702. .Param("state")
  1703. .Callable("IsKeySwitch")
  1704. .Arg(0, "item")
  1705. .Arg(1, "state")
  1706. .Add(2, keyExtractor)
  1707. .Add(3, keyExtractor)
  1708. .Seal()
  1709. .Seal()
  1710. .Build();
  1711. }
  1712. return condenseSwitch;
  1713. }
  1714. TExprNode::TPtr TAggregateExpander::GeneratePostAggregateInitPhase()
  1715. {
  1716. bool aggregateOnly = (Suffix != "");
  1717. const auto& columnNames = aggregateOnly ? FinalColumnNames : InitialColumnNames;
  1718. ui32 index = 0U;
  1719. return Ctx.Builder(Node->Pos())
  1720. .Lambda()
  1721. .Param("item")
  1722. .Callable("AsStruct")
  1723. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1724. for (ui32 i = 0; i < KeyColumns->ChildrenSize(); ++i) {
  1725. parent
  1726. .List(index++)
  1727. .Add(0, KeyColumns->ChildPtr(i))
  1728. .Callable(1, "Member")
  1729. .Arg(0, "item")
  1730. .Add(1, KeyColumns->ChildPtr(i))
  1731. .Seal()
  1732. .Seal();
  1733. }
  1734. if (SessionWindowParams.Update) {
  1735. parent
  1736. .List(index++)
  1737. .Atom(0, SessionStartMemberName)
  1738. .Callable(1, "Member")
  1739. .Arg(0, "item")
  1740. .Atom(1, SessionStartMemberName)
  1741. .Seal()
  1742. .Seal();
  1743. }
  1744. return parent;
  1745. })
  1746. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1747. for (ui32 i = 0; i < columnNames.size(); ++i) {
  1748. auto child = AggregatedColumns->Child(i);
  1749. auto trait = Traits[i];
  1750. if (!EffectiveCompact) {
  1751. auto loadLambda = trait->Child(4);
  1752. auto extractorLambda = GetFinalAggStateExtractor(i);
  1753. if (!DistinctFields.empty() || Suffix == "MergeManyFinalize") {
  1754. parent.List(index++)
  1755. .Add(0, columnNames[i])
  1756. .Callable(1, "Map")
  1757. .Apply(0, *extractorLambda)
  1758. .With(0, "item")
  1759. .Seal()
  1760. .Add(1, loadLambda)
  1761. .Seal()
  1762. .Seal();
  1763. } else {
  1764. parent.List(index++)
  1765. .Add(0, columnNames[i])
  1766. .Apply(1, *loadLambda)
  1767. .With(0)
  1768. .Apply(*extractorLambda)
  1769. .With(0, "item")
  1770. .Seal()
  1771. .Done()
  1772. .Seal();
  1773. }
  1774. } else {
  1775. auto initLambda = trait->Child(1);
  1776. auto distinctField = (child->ChildrenSize() == 3) ? child->Child(2) : nullptr;
  1777. auto initApply = [&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1778. parent.Apply(1, *initLambda)
  1779. .With(0)
  1780. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1781. if (distinctField) {
  1782. parent
  1783. .Callable("Member")
  1784. .Arg(0, "item")
  1785. .Add(1, distinctField)
  1786. .Seal();
  1787. } else {
  1788. parent
  1789. .Callable("CastStruct")
  1790. .Arg(0, "item")
  1791. .Add(1, ExpandType(Node->Pos(), *initLambda->Head().Head().GetTypeAnn(), Ctx))
  1792. .Seal();
  1793. }
  1794. return parent;
  1795. })
  1796. .Done()
  1797. .Do([&](TExprNodeReplaceBuilder& parent) -> TExprNodeReplaceBuilder& {
  1798. if (initLambda->Head().ChildrenSize() == 2) {
  1799. parent.With(1)
  1800. .Callable("Uint32")
  1801. .Atom(0, ToString(i), TNodeFlags::Default)
  1802. .Seal()
  1803. .Done();
  1804. }
  1805. return parent;
  1806. })
  1807. .Seal();
  1808. return parent;
  1809. };
  1810. if (distinctField) {
  1811. const bool isFirst = *Distinct2Columns[distinctField->Content()].begin() == i;
  1812. if (isFirst) {
  1813. parent.List(index++)
  1814. .Add(0, columnNames[i])
  1815. .List(1)
  1816. .Callable(0, "NamedApply")
  1817. .Add(0, UdfSetCreate[distinctField->Content()])
  1818. .List(1)
  1819. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1820. if (!DistinctFieldNeedsPickle[distinctField->Content()]) {
  1821. parent.Callable(0, "Member")
  1822. .Arg(0, "item")
  1823. .Add(1, distinctField)
  1824. .Seal();
  1825. } else {
  1826. parent.Callable(0, "StablePickle")
  1827. .Callable(0, "Member")
  1828. .Arg(0, "item")
  1829. .Add(1, distinctField)
  1830. .Seal()
  1831. .Seal();
  1832. }
  1833. return parent;
  1834. })
  1835. .Callable(1, "Uint32")
  1836. .Atom(0, "0", TNodeFlags::Default)
  1837. .Seal()
  1838. .Seal()
  1839. .Callable(2, "AsStruct").Seal()
  1840. .Callable(3, "DependsOn")
  1841. .Callable(0, "String")
  1842. .Add(0, distinctField)
  1843. .Seal()
  1844. .Seal()
  1845. .Seal()
  1846. .Do(initApply)
  1847. .Seal()
  1848. .Seal();
  1849. } else {
  1850. parent.List(index++)
  1851. .Add(0, columnNames[i])
  1852. .Do(initApply)
  1853. .Seal();
  1854. }
  1855. } else {
  1856. parent.List(index++)
  1857. .Add(0, columnNames[i])
  1858. .Do(initApply)
  1859. .Seal();
  1860. }
  1861. }
  1862. }
  1863. return parent;
  1864. })
  1865. .Seal()
  1866. .Seal()
  1867. .Build();
  1868. }
  1869. TExprNode::TPtr TAggregateExpander::GeneratePostAggregateSavePhase()
  1870. {
  1871. bool aggregateOnly = (Suffix != "");
  1872. const auto& columnNames = aggregateOnly ? FinalColumnNames : InitialColumnNames;
  1873. ui32 index = 0U;
  1874. return Ctx.Builder(Node->Pos())
  1875. .Lambda()
  1876. .Param("state")
  1877. .Callable("AsStruct")
  1878. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1879. for (ui32 i = 0; i < KeyColumns->ChildrenSize(); ++i) {
  1880. if (KeyColumns->Child(i)->Content() == SessionStartMemberName) {
  1881. continue;
  1882. }
  1883. parent
  1884. .List(index++)
  1885. .Add(0, KeyColumns->ChildPtr(i))
  1886. .Callable(1, "Member")
  1887. .Arg(0, "state")
  1888. .Add(1, KeyColumns->ChildPtr(i))
  1889. .Seal()
  1890. .Seal();
  1891. }
  1892. if (SessionOutputColumn) {
  1893. parent
  1894. .List(index++)
  1895. .Atom(0, *SessionOutputColumn)
  1896. .Callable(1, "Member")
  1897. .Arg(0, "state")
  1898. .Atom(1, SessionStartMemberName)
  1899. .Seal()
  1900. .Seal();
  1901. }
  1902. return parent;
  1903. })
  1904. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1905. for (ui32 i = 0; i < columnNames.size(); ++i) {
  1906. auto child = AggregatedColumns->Child(i);
  1907. auto trait = Traits[i];
  1908. auto finishLambda = (Suffix == "MergeState") ? trait->Child(3) : trait->Child(6);
  1909. if (!EffectiveCompact && (!DistinctFields.empty() || Suffix == "MergeManyFinalize")) {
  1910. if (child->Head().IsAtom()) {
  1911. parent.List(index++)
  1912. .Add(0, FinalColumnNames[i])
  1913. .Callable(1, "Unwrap")
  1914. .Callable(0, "Map")
  1915. .Callable(0, "Member")
  1916. .Arg(0, "state")
  1917. .Add(1, columnNames[i])
  1918. .Seal()
  1919. .Add(1, finishLambda)
  1920. .Seal()
  1921. .Seal()
  1922. .Seal();
  1923. } else {
  1924. const auto& multiFields = child->Child(0);
  1925. for (ui32 field = 0; field < multiFields->ChildrenSize(); ++field) {
  1926. parent.List(index++)
  1927. .Atom(0, multiFields->Child(field)->Content())
  1928. .Callable(1, "Nth")
  1929. .Callable(0, "Unwrap")
  1930. .Callable(0, "Map")
  1931. .Callable(0, "Member")
  1932. .Arg(0, "state")
  1933. .Add(1, columnNames[i])
  1934. .Seal()
  1935. .Add(1, finishLambda)
  1936. .Seal()
  1937. .Seal()
  1938. .Atom(1, ToString(field), TNodeFlags::Default)
  1939. .Seal()
  1940. .Seal();
  1941. }
  1942. }
  1943. } else {
  1944. auto distinctField = (child->ChildrenSize() == 3) ? child->Child(2) : nullptr;
  1945. auto stateExtractor = [&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1946. const bool isFirst = distinctField ? (*Distinct2Columns[distinctField->Content()].begin() == i) : false;
  1947. if (distinctField && isFirst) {
  1948. parent.Callable("Nth")
  1949. .Callable(0, "Member")
  1950. .Arg(0, "state")
  1951. .Add(1, columnNames[i])
  1952. .Seal()
  1953. .Atom(1, "1", TNodeFlags::Default)
  1954. .Seal();
  1955. } else {
  1956. parent.Callable("Member")
  1957. .Arg(0, "state")
  1958. .Add(1, columnNames[i])
  1959. .Seal();
  1960. }
  1961. return parent;
  1962. };
  1963. if (child->Head().IsAtom()) {
  1964. parent.List(index++)
  1965. .Add(0, FinalColumnNames[i])
  1966. .Apply(1, *finishLambda)
  1967. .With(0)
  1968. .Do(stateExtractor)
  1969. .Done()
  1970. .Seal()
  1971. .Seal();
  1972. } else {
  1973. const auto& multiFields = child->Head();
  1974. for (ui32 field = 0; field < multiFields.ChildrenSize(); ++field) {
  1975. parent.List(index++)
  1976. .Atom(0, multiFields.Child(field)->Content())
  1977. .Callable(1, "Nth")
  1978. .Apply(0, *finishLambda)
  1979. .With(0)
  1980. .Do(stateExtractor)
  1981. .Done()
  1982. .Seal()
  1983. .Atom(1, ToString(field), TNodeFlags::Default)
  1984. .Seal()
  1985. .Seal();
  1986. }
  1987. }
  1988. }
  1989. }
  1990. return parent;
  1991. })
  1992. .Seal()
  1993. .Seal()
  1994. .Build();
  1995. }
  1996. TExprNode::TPtr TAggregateExpander::GeneratePostAggregateMergePhase()
  1997. {
  1998. bool aggregateOnly = (Suffix != "");
  1999. const auto& columnNames = aggregateOnly ? FinalColumnNames : InitialColumnNames;
  2000. ui32 index = 0U;
  2001. return Ctx.Builder(Node->Pos())
  2002. .Lambda()
  2003. .Param("item")
  2004. .Param("state")
  2005. .Callable("AsStruct")
  2006. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  2007. for (ui32 i = 0; i < KeyColumns->ChildrenSize(); ++i) {
  2008. parent
  2009. .List(index++)
  2010. .Add(0, KeyColumns->ChildPtr(i))
  2011. .Callable(1, "Member")
  2012. .Arg(0, "state")
  2013. .Add(1, KeyColumns->ChildPtr(i))
  2014. .Seal()
  2015. .Seal();
  2016. }
  2017. if (SessionWindowParams.Update) {
  2018. parent
  2019. .List(index++)
  2020. .Atom(0, SessionStartMemberName)
  2021. .Callable(1, "Member")
  2022. .Arg(0, "state")
  2023. .Atom(1, SessionStartMemberName)
  2024. .Seal()
  2025. .Seal();
  2026. }
  2027. return parent;
  2028. })
  2029. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  2030. for (ui32 i = 0; i < columnNames.size(); ++i) {
  2031. auto child = AggregatedColumns->Child(i);
  2032. auto trait = Traits[i];
  2033. if (!EffectiveCompact) {
  2034. auto loadLambda = trait->Child(4);
  2035. auto mergeLambda = trait->Child(5);
  2036. auto extractorLambda = GetFinalAggStateExtractor(i);
  2037. if (!DistinctFields.empty() || Suffix == "MergeManyFinalize") {
  2038. parent.List(index++)
  2039. .Add(0, columnNames[i])
  2040. .Callable(1, "OptionalReduce")
  2041. .Callable(0, "Map")
  2042. .Apply(0, extractorLambda)
  2043. .With(0, "item")
  2044. .Seal()
  2045. .Add(1, loadLambda)
  2046. .Seal()
  2047. .Callable(1, "Member")
  2048. .Arg(0, "state")
  2049. .Add(1, columnNames[i])
  2050. .Seal()
  2051. .Add(2, mergeLambda)
  2052. .Seal()
  2053. .Seal();
  2054. } else {
  2055. parent.List(index++)
  2056. .Add(0, columnNames[i])
  2057. .Apply(1, *mergeLambda)
  2058. .With(0)
  2059. .Apply(*loadLambda)
  2060. .With(0)
  2061. .Apply(extractorLambda)
  2062. .With(0, "item")
  2063. .Seal()
  2064. .Done()
  2065. .Seal()
  2066. .Done()
  2067. .With(1)
  2068. .Callable("Member")
  2069. .Arg(0, "state")
  2070. .Add(1, columnNames[i])
  2071. .Seal()
  2072. .Done()
  2073. .Seal()
  2074. .Seal();
  2075. }
  2076. } else {
  2077. auto updateLambda = trait->Child(2);
  2078. auto distinctField = (child->ChildrenSize() == 3) ? child->Child(2) : nullptr;
  2079. const bool isFirst = distinctField ? (*Distinct2Columns[distinctField->Content()].begin() == i) : false;
  2080. auto updateApply = [&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  2081. parent.Apply(1, *updateLambda)
  2082. .With(0)
  2083. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  2084. if (distinctField) {
  2085. parent
  2086. .Callable("Member")
  2087. .Arg(0, "item")
  2088. .Add(1, distinctField)
  2089. .Seal();
  2090. } else {
  2091. parent
  2092. .Callable("CastStruct")
  2093. .Arg(0, "item")
  2094. .Add(1, ExpandType(Node->Pos(), *updateLambda->Head().Head().GetTypeAnn(), Ctx))
  2095. .Seal();
  2096. }
  2097. return parent;
  2098. })
  2099. .Done()
  2100. .With(1)
  2101. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  2102. if (distinctField && isFirst) {
  2103. parent.Callable("Nth")
  2104. .Callable(0, "Member")
  2105. .Arg(0, "state")
  2106. .Add(1, columnNames[i])
  2107. .Seal()
  2108. .Atom(1, "1", TNodeFlags::Default)
  2109. .Seal();
  2110. } else {
  2111. parent.Callable("Member")
  2112. .Arg(0, "state")
  2113. .Add(1, columnNames[i])
  2114. .Seal();
  2115. }
  2116. return parent;
  2117. })
  2118. .Done()
  2119. .Do([&](TExprNodeReplaceBuilder& parent) -> TExprNodeReplaceBuilder& {
  2120. if (updateLambda->Head().ChildrenSize() == 3) {
  2121. parent
  2122. .With(2)
  2123. .Callable("Uint32")
  2124. .Atom(0, ToString(i), TNodeFlags::Default)
  2125. .Seal()
  2126. .Done();
  2127. }
  2128. return parent;
  2129. })
  2130. .Seal();
  2131. return parent;
  2132. };
  2133. if (distinctField) {
  2134. auto distinctIndex = *Distinct2Columns[distinctField->Content()].begin();
  2135. ui32 newValueIndex = 0;
  2136. auto newValue = [&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  2137. parent.Callable(newValueIndex, "NamedApply")
  2138. .Add(0, UdfAddValue[distinctField->Content()])
  2139. .List(1)
  2140. .Callable(0, "Nth")
  2141. .Callable(0, "Member")
  2142. .Arg(0, "state")
  2143. .Add(1, columnNames[distinctIndex])
  2144. .Seal()
  2145. .Atom(1, "0", TNodeFlags::Default)
  2146. .Seal()
  2147. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  2148. if (!DistinctFieldNeedsPickle[distinctField->Content()]) {
  2149. parent.Callable(1, "Member")
  2150. .Arg(0, "item")
  2151. .Add(1, distinctField)
  2152. .Seal();
  2153. } else {
  2154. parent.Callable(1, "StablePickle")
  2155. .Callable(0, "Member")
  2156. .Arg(0, "item")
  2157. .Add(1, distinctField)
  2158. .Seal()
  2159. .Seal();
  2160. }
  2161. return parent;
  2162. })
  2163. .Seal()
  2164. .Callable(2, "AsStruct").Seal()
  2165. .Seal();
  2166. return parent;
  2167. };
  2168. parent.List(index++)
  2169. .Add(0, columnNames[i])
  2170. .Callable(1, "If")
  2171. .Callable(0, "NamedApply")
  2172. .Add(0, UdfWasChanged[distinctField->Content()])
  2173. .List(1)
  2174. .Callable(0, "NamedApply")
  2175. .Add(0, UdfAddValue[distinctField->Content()])
  2176. .List(1)
  2177. .Callable(0, "Nth")
  2178. .Callable(0, "Member")
  2179. .Arg(0, "state")
  2180. .Add(1, columnNames[distinctIndex])
  2181. .Seal()
  2182. .Atom(1, "0", TNodeFlags::Default)
  2183. .Seal()
  2184. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  2185. if (!DistinctFieldNeedsPickle[distinctField->Content()]) {
  2186. parent.Callable(1, "Member")
  2187. .Arg(0, "item")
  2188. .Add(1, distinctField)
  2189. .Seal();
  2190. } else {
  2191. parent.Callable(1, "StablePickle")
  2192. .Callable(0, "Member")
  2193. .Arg(0, "item")
  2194. .Add(1, distinctField)
  2195. .Seal()
  2196. .Seal();
  2197. }
  2198. return parent;
  2199. })
  2200. .Seal()
  2201. .Callable(2, "AsStruct").Seal()
  2202. .Seal()
  2203. .Seal()
  2204. .Callable(2, "AsStruct").Seal()
  2205. .Seal()
  2206. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  2207. if (distinctIndex == i) {
  2208. parent.List(1)
  2209. .Do(newValue)
  2210. .Do(updateApply)
  2211. .Seal();
  2212. } else {
  2213. parent.Do(updateApply);
  2214. }
  2215. return parent;
  2216. })
  2217. .Callable(2, "Member")
  2218. .Arg(0, "state")
  2219. .Add(1, columnNames[i])
  2220. .Seal()
  2221. .Seal()
  2222. .Seal();
  2223. } else {
  2224. parent.List(index++)
  2225. .Add(0, columnNames[i])
  2226. .Do(updateApply)
  2227. .Seal();
  2228. }
  2229. }
  2230. }
  2231. return parent;
  2232. })
  2233. .Seal()
  2234. .Seal()
  2235. .Build();
  2236. }
  2237. TExprNode::TPtr TAggregateExpander::GenerateJustOverStates(const TExprNode::TPtr& input, const TIdxSet& indicies) {
  2238. return Ctx.Builder(Node->Pos())
  2239. .Callable("Map")
  2240. .Add(0, input)
  2241. .Lambda(1)
  2242. .Param("row")
  2243. .Callable("AsStruct")
  2244. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  2245. ui32 pos = 0;
  2246. for (ui32 i = 0; i < KeyColumns->ChildrenSize(); ++i) {
  2247. parent
  2248. .List(pos++)
  2249. .Add(0, KeyColumns->ChildPtr(i))
  2250. .Callable(1, "Member")
  2251. .Arg(0, "row")
  2252. .Add(1, KeyColumns->ChildPtr(i))
  2253. .Seal()
  2254. .Seal();
  2255. }
  2256. for (ui32 i : indicies) {
  2257. parent
  2258. .List(pos++)
  2259. .Add(0, InitialColumnNames[i])
  2260. .Callable(1, "Just")
  2261. .Callable(0, "Member")
  2262. .Arg(0, "row")
  2263. .Add(1, InitialColumnNames[i])
  2264. .Seal()
  2265. .Seal()
  2266. .Seal();
  2267. }
  2268. return parent;
  2269. })
  2270. .Seal()
  2271. .Seal()
  2272. .Seal()
  2273. .Build();
  2274. }
  2275. TExprNode::TPtr TAggregateExpander::SerializeIdxSet(const TIdxSet& indicies) {
  2276. return Ctx.Builder(Node->Pos())
  2277. .List()
  2278. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  2279. ui32 pos = 0;
  2280. for (ui32 i : indicies) {
  2281. parent.Atom(pos++, ToString(i));
  2282. }
  2283. return parent;
  2284. })
  2285. .Seal()
  2286. .Build();
  2287. }
  2288. TExprNode::TPtr TAggregateExpander::GeneratePhases() {
  2289. const TExprNode::TPtr cleanOutputSettings = RemoveSetting(*Node->Child(3), "output_columns", Ctx);
  2290. const bool many = HaveDistinct;
  2291. YQL_CLOG(DEBUG, Core) << "Aggregate: generate " << (many ? "phases with distinct" : "simple phases");
  2292. TExprNode::TListType mergeTraits;
  2293. for (ui32 index = 0; index < AggregatedColumns->ChildrenSize(); ++index) {
  2294. auto originalTrait = AggregatedColumns->Child(index)->ChildPtr(1);
  2295. auto extractor = Ctx.Builder(Node->Pos())
  2296. .Lambda()
  2297. .Param("row")
  2298. .Callable("Member")
  2299. .Arg(0, "row")
  2300. .Add(1, InitialColumnNames[index])
  2301. .Seal()
  2302. .Seal()
  2303. .Build();
  2304. if (many) {
  2305. extractor = Ctx.Builder(Node->Pos())
  2306. .Lambda()
  2307. .Param("row")
  2308. .Callable("Unwrap")
  2309. .Apply(0, extractor)
  2310. .With(0, "row")
  2311. .Seal()
  2312. .Seal()
  2313. .Seal()
  2314. .Build();
  2315. }
  2316. bool isAggApply = originalTrait->IsCallable("AggApply");
  2317. auto serializedStateType = isAggApply ? AggApplySerializedStateType(originalTrait, Ctx) : originalTrait->Child(3)->GetTypeAnn();
  2318. if (many) {
  2319. serializedStateType = Ctx.MakeType<TOptionalExprType>(serializedStateType);
  2320. }
  2321. auto extractorTypeNode = Ctx.Builder(Node->Pos())
  2322. .Callable("StructType")
  2323. .List(0)
  2324. .Add(0, InitialColumnNames[index])
  2325. .Add(1, ExpandType(Node->Pos(), *serializedStateType, Ctx))
  2326. .Seal()
  2327. .Seal()
  2328. .Build();
  2329. if (isAggApply) {
  2330. auto initialType = originalTrait->GetTypeAnn();
  2331. if (many) {
  2332. initialType = Ctx.MakeType<TOptionalExprType>(initialType);
  2333. }
  2334. auto originalExtractorTypeNode = Ctx.Builder(Node->Pos())
  2335. .Callable("StructType")
  2336. .List(0)
  2337. .Add(0, InitialColumnNames[index])
  2338. .Add(1, ExpandType(Node->Pos(), *initialType, Ctx))
  2339. .Seal()
  2340. .Seal()
  2341. .Build();
  2342. auto name = TString(originalTrait->ChildPtr(0)->Content());
  2343. if (name.StartsWith("pg_")) {
  2344. auto func = name.substr(3);
  2345. TVector<ui32> argTypes;
  2346. bool needRetype = false;
  2347. auto status = ExtractPgTypesFromMultiLambda(originalTrait->ChildRef(2), argTypes, needRetype, Ctx);
  2348. YQL_ENSURE(status == IGraphTransformer::TStatus::Ok);
  2349. const NPg::TAggregateDesc& aggDesc = NPg::LookupAggregation(TString(func), argTypes);
  2350. name = "pg_" + aggDesc.Name + "#" + ToString(aggDesc.AggId);
  2351. }
  2352. mergeTraits.push_back(Ctx.Builder(Node->Pos())
  2353. .Callable(many ? "AggApplyManyState" : "AggApplyState")
  2354. .Atom(0, name)
  2355. .Add(1, extractorTypeNode)
  2356. .Add(2, extractor)
  2357. .Add(3, originalExtractorTypeNode)
  2358. .Seal()
  2359. .Build());
  2360. } else {
  2361. YQL_ENSURE(originalTrait->IsCallable("AggregationTraits"));
  2362. mergeTraits.push_back(Ctx.Builder(Node->Pos())
  2363. .Callable("AggregationTraits")
  2364. .Add(0, extractorTypeNode)
  2365. .Add(1, extractor)
  2366. .Lambda(2)
  2367. .Param("item")
  2368. .Param("state")
  2369. .Callable("Void")
  2370. .Seal()
  2371. .Seal()
  2372. .Add(3, originalTrait->ChildPtr(3))
  2373. .Add(4, originalTrait->ChildPtr(4))
  2374. .Add(5, originalTrait->ChildPtr(5))
  2375. .Add(6, originalTrait->ChildPtr(6))
  2376. .Add(7, originalTrait->ChildPtr(7))
  2377. .Seal()
  2378. .Build());
  2379. }
  2380. }
  2381. TExprNode::TListType finalizeColumns;
  2382. for (ui32 index = 0; index < AggregatedColumns->ChildrenSize(); ++index) {
  2383. finalizeColumns.push_back(Ctx.Builder(Node->Pos())
  2384. .List()
  2385. .Add(0, AggregatedColumns->Child(index)->ChildPtr(0))
  2386. .Add(1, mergeTraits[index])
  2387. .Seal()
  2388. .Build());
  2389. }
  2390. if (!many) {
  2391. // simple Combine + MergeFinalize
  2392. TExprNode::TListType combineColumns;
  2393. for (ui32 index = 0; index < AggregatedColumns->ChildrenSize(); ++index) {
  2394. combineColumns.push_back(Ctx.Builder(Node->Pos())
  2395. .List()
  2396. .Add(0, InitialColumnNames[index])
  2397. .Add(1, AggregatedColumns->Child(index)->ChildPtr(1))
  2398. .Seal()
  2399. .Build());
  2400. }
  2401. auto combine = Ctx.Builder(Node->Pos())
  2402. .Callable("AggregateCombine")
  2403. .Add(0, AggList)
  2404. .Add(1, KeyColumns)
  2405. .Add(2, Ctx.NewList(Node->Pos(), std::move(combineColumns)))
  2406. .Add(3, cleanOutputSettings)
  2407. .Seal()
  2408. .Build();
  2409. auto mergeFinalize = Ctx.Builder(Node->Pos())
  2410. .Callable("AggregateMergeFinalize")
  2411. .Add(0, combine)
  2412. .Add(1, KeyColumns)
  2413. .Add(2, Ctx.NewList(Node->Pos(), std::move(finalizeColumns)))
  2414. .Add(3, cleanOutputSettings)
  2415. .Seal()
  2416. .Build();
  2417. return mergeFinalize;
  2418. }
  2419. // process with distincts
  2420. // Combine + Map with Just over states
  2421. // for each distinct field:
  2422. // Aggregate by keys + field w/o aggs
  2423. // Combine by keys + field with aggs
  2424. // Map with Just over states
  2425. // UnionAll
  2426. // MergeManyFinalize
  2427. TExprNode::TListType unionAllInputs;
  2428. TExprNode::TListType streams;
  2429. if (!NonDistinctColumns.empty()) {
  2430. TExprNode::TListType combineColumns;
  2431. for (ui32 i : NonDistinctColumns) {
  2432. combineColumns.push_back(Ctx.Builder(Node->Pos())
  2433. .List()
  2434. .Add(0, InitialColumnNames[i])
  2435. .Add(1, AggregatedColumns->Child(i)->ChildPtr(1))
  2436. .Seal()
  2437. .Build());
  2438. }
  2439. auto combine = Ctx.Builder(Node->Pos())
  2440. .Callable("AggregateCombine")
  2441. .Add(0, AggList)
  2442. .Add(1, KeyColumns)
  2443. .Add(2, Ctx.NewList(Node->Pos(), std::move(combineColumns)))
  2444. .Add(3, cleanOutputSettings)
  2445. .Seal()
  2446. .Build();
  2447. unionAllInputs.push_back(GenerateJustOverStates(combine, NonDistinctColumns));
  2448. streams.push_back(SerializeIdxSet(NonDistinctColumns));
  2449. }
  2450. for (ui32 index = 0; index < DistinctFields.size(); ++index) {
  2451. auto distinctField = DistinctFields[index];
  2452. auto& indicies = Distinct2Columns[distinctField->Content()];
  2453. TExprNode::TListType allKeyColumns = KeyColumns->ChildrenList();
  2454. allKeyColumns.push_back(distinctField);
  2455. auto distinct = Ctx.Builder(Node->Pos())
  2456. .Callable("Aggregate")
  2457. .Add(0, AggList)
  2458. .Add(1, Ctx.NewList(Node->Pos(), std::move(allKeyColumns)))
  2459. .List(2)
  2460. .Seal()
  2461. .Add(3, cleanOutputSettings)
  2462. .Seal()
  2463. .Build();
  2464. TExprNode::TListType combineColumns;
  2465. for (ui32 i : indicies) {
  2466. auto trait = AggregatedColumns->Child(i)->ChildPtr(1);
  2467. bool isAggApply = trait->IsCallable("AggApply");
  2468. if (isAggApply) {
  2469. trait = Ctx.Builder(Node->Pos())
  2470. .Callable("AggApply")
  2471. .Add(0, trait->ChildPtr(0))
  2472. .Callable(1, "StructType")
  2473. .List(0)
  2474. .Add(0, distinctField)
  2475. .Add(1, trait->ChildPtr(1))
  2476. .Seal()
  2477. .Seal()
  2478. .Lambda(2)
  2479. .Param("row")
  2480. .Apply(trait->ChildPtr(2))
  2481. .With(0)
  2482. .Callable("Member")
  2483. .Arg(0, "row")
  2484. .Add(1, distinctField)
  2485. .Seal()
  2486. .Done()
  2487. .Seal()
  2488. .Seal()
  2489. .Seal()
  2490. .Build();
  2491. } else {
  2492. TExprNode::TPtr newInit;
  2493. if (trait->ChildPtr(1)->Head().ChildrenSize() == 1) {
  2494. newInit = Ctx.Builder(Node->Pos())
  2495. .Lambda()
  2496. .Param("row")
  2497. .Apply(trait->ChildPtr(1))
  2498. .With(0)
  2499. .Callable("Member")
  2500. .Arg(0, "row")
  2501. .Add(1, distinctField)
  2502. .Seal()
  2503. .Done()
  2504. .Seal()
  2505. .Seal()
  2506. .Build();
  2507. } else {
  2508. newInit = Ctx.Builder(Node->Pos())
  2509. .Lambda()
  2510. .Param("row")
  2511. .Param("parent")
  2512. .Apply(trait->ChildPtr(1))
  2513. .With(0)
  2514. .Callable("Member")
  2515. .Arg(0, "row")
  2516. .Add(1, distinctField)
  2517. .Seal()
  2518. .Done()
  2519. .With(1, "parent")
  2520. .Seal()
  2521. .Seal()
  2522. .Build();
  2523. }
  2524. TExprNode::TPtr newUpdate;
  2525. if (trait->ChildPtr(2)->Head().ChildrenSize() == 2) {
  2526. newUpdate = Ctx.Builder(Node->Pos())
  2527. .Lambda()
  2528. .Param("row")
  2529. .Param("state")
  2530. .Apply(trait->ChildPtr(2))
  2531. .With(0)
  2532. .Callable("Member")
  2533. .Arg(0, "row")
  2534. .Add(1, distinctField)
  2535. .Seal()
  2536. .Done()
  2537. .With(1, "state")
  2538. .Seal()
  2539. .Seal()
  2540. .Build();
  2541. } else {
  2542. newUpdate = Ctx.Builder(Node->Pos())
  2543. .Lambda()
  2544. .Param("row")
  2545. .Param("state")
  2546. .Param("parent")
  2547. .Apply(trait->ChildPtr(2))
  2548. .With(0)
  2549. .Callable("Member")
  2550. .Arg(0, "row")
  2551. .Add(1, distinctField)
  2552. .Seal()
  2553. .Done()
  2554. .With(1, "state")
  2555. .With(2, "parent")
  2556. .Seal()
  2557. .Seal()
  2558. .Build();
  2559. }
  2560. trait = Ctx.Builder(Node->Pos())
  2561. .Callable("AggregationTraits")
  2562. .Callable(0, "StructType")
  2563. .List(0)
  2564. .Add(0, distinctField)
  2565. .Add(1, trait->ChildPtr(0))
  2566. .Seal()
  2567. .Seal()
  2568. .Add(1, newInit)
  2569. .Add(2, newUpdate)
  2570. .Add(3, trait->ChildPtr(3))
  2571. .Add(4, trait->ChildPtr(4))
  2572. .Add(5, trait->ChildPtr(5))
  2573. .Add(6, trait->ChildPtr(6))
  2574. .Add(7, trait->ChildPtr(7))
  2575. .Seal()
  2576. .Build();
  2577. }
  2578. combineColumns.push_back(Ctx.Builder(Node->Pos())
  2579. .List()
  2580. .Add(0, InitialColumnNames[i])
  2581. .Add(1, trait)
  2582. .Seal()
  2583. .Build());
  2584. }
  2585. auto combine = Ctx.Builder(Node->Pos())
  2586. .Callable("AggregateCombine")
  2587. .Add(0, distinct)
  2588. .Add(1, KeyColumns)
  2589. .Add(2, Ctx.NewList(Node->Pos(), std::move(combineColumns)))
  2590. .Add(3, cleanOutputSettings)
  2591. .Seal()
  2592. .Build();
  2593. unionAllInputs.push_back(GenerateJustOverStates(combine, indicies));
  2594. streams.push_back(SerializeIdxSet(indicies));
  2595. }
  2596. if (UseBlocks) {
  2597. for (ui32 i = 0; i < unionAllInputs.size(); ++i) {
  2598. unionAllInputs[i] = Ctx.Builder(Node->Pos())
  2599. .Callable("Map")
  2600. .Add(0, unionAllInputs[i])
  2601. .Lambda(1)
  2602. .Param("row")
  2603. .Callable("AddMember")
  2604. .Arg(0, "row")
  2605. .Atom(1, "_yql_group_stream_index")
  2606. .Callable(2, "Uint32")
  2607. .Atom(0, ToString(i))
  2608. .Seal()
  2609. .Seal()
  2610. .Seal()
  2611. .Seal()
  2612. .Build();
  2613. }
  2614. }
  2615. auto settings = cleanOutputSettings;
  2616. if (UseBlocks) {
  2617. settings = AddSetting(*settings, Node->Pos(), "many_streams", Ctx.NewList(Node->Pos(), std::move(streams)), Ctx);
  2618. }
  2619. auto unionAll = Ctx.NewCallable(Node->Pos(), "UnionAll", std::move(unionAllInputs));
  2620. auto mergeManyFinalize = Ctx.Builder(Node->Pos())
  2621. .Callable("AggregateMergeManyFinalize")
  2622. .Add(0, unionAll)
  2623. .Add(1, KeyColumns)
  2624. .Add(2, Ctx.NewList(Node->Pos(), std::move(finalizeColumns)))
  2625. .Add(3, settings)
  2626. .Seal()
  2627. .Build();
  2628. return mergeManyFinalize;
  2629. }
  2630. TExprNode::TPtr TAggregateExpander::TryGenerateBlockCombine() {
  2631. if (HaveSessionSetting || HaveDistinct) {
  2632. return nullptr;
  2633. }
  2634. for (const auto& x : AggregatedColumns->Children()) {
  2635. auto trait = x->ChildPtr(1);
  2636. if (!trait->IsCallable("AggApply")) {
  2637. return nullptr;
  2638. }
  2639. }
  2640. return TryGenerateBlockCombineAllOrHashed();
  2641. }
  2642. TExprNode::TPtr TAggregateExpander::TryGenerateBlockMergeFinalize() {
  2643. if (UsePartitionsByKeys || !UseBlocks) {
  2644. return nullptr;
  2645. }
  2646. if (HaveSessionSetting || HaveDistinct) {
  2647. return nullptr;
  2648. }
  2649. for (const auto& x : AggregatedColumns->Children()) {
  2650. auto trait = x->ChildPtr(1);
  2651. if (!trait->IsCallable({ "AggApplyState", "AggApplyManyState" })) {
  2652. return nullptr;
  2653. }
  2654. }
  2655. return TryGenerateBlockMergeFinalizeHashed();
  2656. }
  2657. TExprNode::TPtr TAggregateExpander::TryGenerateBlockMergeFinalizeHashed() {
  2658. if (!TypesCtx.ArrowResolver) {
  2659. return nullptr;
  2660. }
  2661. if (KeyColumns->ChildrenSize() == 0) {
  2662. return nullptr;
  2663. }
  2664. bool isMany = Suffix == "MergeManyFinalize";
  2665. auto streamArg = Ctx.NewArgument(Node->Pos(), "stream");
  2666. TExprNode::TListType keyIdxs;
  2667. TVector<TString> outputColumns;
  2668. TExprNode::TListType aggs;
  2669. ui32 streamIdxColumn;
  2670. auto blocks = MakeInputBlocks(streamArg, keyIdxs, outputColumns, aggs, true, isMany, &streamIdxColumn);
  2671. if (!blocks) {
  2672. return nullptr;
  2673. }
  2674. TExprNode::TPtr aggBlocks;
  2675. if (!isMany) {
  2676. aggBlocks = Ctx.Builder(Node->Pos())
  2677. .Callable("ToFlow")
  2678. .Callable(0, "BlockMergeFinalizeHashed")
  2679. .Callable(0, "FromFlow")
  2680. .Add(0, blocks)
  2681. .Seal()
  2682. .Add(1, Ctx.NewList(Node->Pos(), std::move(keyIdxs)))
  2683. .Add(2, Ctx.NewList(Node->Pos(), std::move(aggs)))
  2684. .Seal()
  2685. .Seal()
  2686. .Build();
  2687. } else {
  2688. auto manyStreamsSetting = GetSetting(*Node->Child(3), "many_streams");
  2689. YQL_ENSURE(manyStreamsSetting, "Missing many_streams setting");
  2690. aggBlocks = Ctx.Builder(Node->Pos())
  2691. .Callable("ToFlow")
  2692. .Callable(0, "BlockMergeManyFinalizeHashed")
  2693. .Callable(0, "FromFlow")
  2694. .Add(0, blocks)
  2695. .Seal()
  2696. .Add(1, Ctx.NewList(Node->Pos(), std::move(keyIdxs)))
  2697. .Add(2, Ctx.NewList(Node->Pos(), std::move(aggs)))
  2698. .Atom(3, ToString(streamIdxColumn))
  2699. .Add(4, manyStreamsSetting->TailPtr())
  2700. .Seal()
  2701. .Seal()
  2702. .Build();
  2703. }
  2704. auto aggWideFlow = Ctx.Builder(Node->Pos())
  2705. .Callable("ToFlow")
  2706. .Callable(0, "WideFromBlocks")
  2707. .Callable(0, "FromFlow")
  2708. .Add(0, aggBlocks)
  2709. .Seal()
  2710. .Seal()
  2711. .Seal()
  2712. .Build();
  2713. auto finalFlow = MakeNarrowMap(Node->Pos(), outputColumns, aggWideFlow, Ctx);
  2714. auto root = Ctx.NewCallable(Node->Pos(), "FromFlow", { finalFlow });
  2715. auto lambdaStream = Ctx.NewLambda(Node->Pos(), Ctx.NewArguments(Node->Pos(), { streamArg }), std::move(root));
  2716. auto keySelector = BuildKeySelector(Node->Pos(), *OriginalRowType, KeyColumns, Ctx);
  2717. return Ctx.Builder(Node->Pos())
  2718. .Callable("ShuffleByKeys")
  2719. .Add(0, AggList)
  2720. .Add(1, keySelector)
  2721. .Lambda(2)
  2722. .Param("stream")
  2723. .Apply(GetContextLambda())
  2724. .With(0)
  2725. .Apply(lambdaStream)
  2726. .With(0, "stream")
  2727. .Seal()
  2728. .Done()
  2729. .Seal()
  2730. .Seal()
  2731. .Seal()
  2732. .Build();
  2733. }
  2734. TExprNode::TPtr ExpandAggregatePeephole(const TExprNode::TPtr& node, TExprContext& ctx, TTypeAnnotationContext& typesCtx) {
  2735. if (NNodes::TCoAggregate::Match(node.Get())) {
  2736. NNodes::TCoAggregate self(node);
  2737. auto ret = TAggregateExpander::CountAggregateRewrite(self, ctx, typesCtx.IsBlockEngineEnabled());
  2738. if (ret != node) {
  2739. YQL_CLOG(DEBUG, Core) << "CountAggregateRewrite on peephole";
  2740. return ret;
  2741. }
  2742. }
  2743. return ExpandAggregatePeepholeImpl(node, ctx, typesCtx, false, typesCtx.IsBlockEngineEnabled(), false);
  2744. }
  2745. } // namespace NYql