yql_aggregate_expander.cpp 122 KB

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