yql_aggregate_expander.cpp 122 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984
  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. return Ctx.Builder(Node->Pos())
  596. .Callable("ToFlow")
  597. .Callable(0, "WideToBlocks")
  598. .Callable(0, "FromFlow")
  599. .Add(0, mappedWideFlow)
  600. .Seal()
  601. .Seal()
  602. .Seal()
  603. .Build();
  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