yql_aggregate_expander.cpp 123 KB

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